Search code examples
javascripthtmlonloaddeferred-loading

Is a javascript parsed when appendChild is called?


Google page speed tells me that I should Defer parsing of JavaScript.

I have two external Javascripts loaded in the header and a call to an initialization function at the bottom of my document.

If I follow Google's recommendations, I should/could create a function like this:

function downloadJSAtOnload() {

  var element = document.createElement("script");
  element.src = "myscript1.js";
  document.body.appendChild(element);

  element = document.createElement("script");
  element.src = "myscript2.js";
  document.body.appendChild(element);

  myinitialization();

}

Can I be 100% sure that myinitialization() will not be called before my scripts have been loaded and parsed successfully? Else, what is the solution?


Solution

  • As per Felix, the answer is no. I cannot rely on the fact that appended code will be executed before the call to myinitialization();.

    A solution is to wrap the code in one file and use async.