0

I am trying to load script and link using javascript.Previously I was using jquery not I am removing jquery from our project only using javascript.

previously I write like this

   $('head link[data-reqjq][rel=preload]').each(function(){
      var a = document.createElement('script');
      a.async=false;
      a.src=$(this).attr('href');
      this.parentNode.insertBefore(a, this);
    });
  $(function(){
    $('script[data-reqjq][data-src]').each(function(){
      this.async=true;
      this.src=$(this).data('src');
    });
  });

Now I am trying to load both things using javascript.

like this but it is not loading

var elements = document.querySelectorAll('head link[data-reqjq][rel=preload]');
Array.prototype.forEach.call(elements, function(el, i){
  var a = document.createElement('script');
  a.async=false;
  a.src=this.getAttribute('href');
  this.parentNode.insertBefore(a, this);
});

var elements = document.querySelectorAll('script[data-reqjq][data-src]');
Array.prototype.forEach.call(elements, function(el, i){
  el.async=true;
  el.src=el.data('src');
});

here is my code

https://jsbin.com/havuxujixi/3/edit?html,js,output

user944513
  • 12,247
  • 49
  • 168
  • 318

2 Answers2

1

Simple Solution

/*
 add JS File 
*/
function addJsFileFunc(filename) {
        document.getElementsByTagName('head')[0].innerHTML.toString().includes(filename + ".js"))
        loadScript('/',filename + ".js");
}

addJsFileFunc("paht/script-file-name.js")




/*
 script tag
*/
let scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.src = 'url.js';    

document.getElementsByTagName('head')[0].appendChild(scriptTag);
GMKHussain
  • 3,342
  • 1
  • 21
  • 19
0

1 - add a end tag to the script; </script> instead of /> (check here)

2 - your second query selector have an error in its callback : .data('src') should be .getAttribute('src')

also as a suggestion use simple forEach instead of Array.prototype.call

var elements = document.querySelectorAll('script[data-reqjq][data-src]');
elements.forEach(function(el, i){
  el.async=true;
  el.src=el.getAttribute('src');

});

the first selector can be written as:

var elements = document.querySelectorAll('head link[data-reqjq][rel=preload]');
elements.forEach(function(el, i){
  var a = document.createElement('script');
  a.async=false;
  a.src=el.getAttribute('href');
  // mounting new one inplace
  el.parentNode.append(a);
  // unmouting the old one
  el.remove();
});
Mechanic
  • 5,015
  • 4
  • 15
  • 38