Reputation: 59616
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?
Upvotes: 0
Views: 149
Reputation: 59616
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
.
Upvotes: 0
Reputation: 251082
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.
Upvotes: 1