문제

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?

도움이 되었습니까?

해결책 2

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.

다른 팁

It is usually sufficient to include script files at the end of your document (before the '' tag).

        ...
        <script src="myscript1.js"></script>
        <script src="myscript2.js"></script>
        <script>
            myinitialization();
        </script>
    </body>
</html>

This means the document will load before scripts start to be downloaded, but it also means you guarantee your order of execution.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top