I need to load a script asynchronously onto a page. I am using the createElement
method to dynamically insert a script tag in the head. What is happening is First the page source loads. When this finishes, all the elements included in the head loads in parallel. Once this is all loaded, the script which I dynamically add loads.
This logically makes sense, but what I am looking for is a way where I can accelerate the loading of my dynamic script. I still want it to be asynchronous (don't want to do document.write
) but still would love if this script could be loaded in parallel with other scripts of the head element. Any way I can get this working?
I need to load a script asynchronously onto a page. I am using the createElement
method to dynamically insert a script tag in the head. What is happening is First the page source loads. When this finishes, all the elements included in the head loads in parallel. Once this is all loaded, the script which I dynamically add loads.
This logically makes sense, but what I am looking for is a way where I can accelerate the loading of my dynamic script. I still want it to be asynchronous (don't want to do document.write
) but still would love if this script could be loaded in parallel with other scripts of the head element. Any way I can get this working?
2 Answers
Reset to default 5Put a few lines of javascript at the top creating the dynamic script tag.
<script>
var script = document.createElement("script");
script.src = "yourfile.js";
script.async = true; //asynchronous
document.getElementsByTagName("head")[0].appendChild(script);
</script>
For other alternatives check out this link: http://friendlybit./js/lazy-loading-asyncronous-javascript/
You can add the attribute async
to the script
element if you use HTML5. This is the simplest method, wherever you load (but not the most patible). Just to be clear, even the code provided above will only work if you are working with HTML5. The thing is, you don't have to go through all that trouble of adding such a script at all in the first place.
<script src="/path/to/your/js/here" async></script>
Also note that XHTML does not allow attribute minimisation, so in XHTML you have to use
<script src="/path/to/your/js/here" async="async"></script>
Also, you have a defer
attribute which defers parsing of javascript until the document has loaded, which can also be used as defer="defer"
thse same way I have shown an example script inclusion using async
. Both async
and defer
tags can be used in the same script element.
Also note that these attributes can only be added to an off-document script and not an inline script, which means you can't use async
and defer
if you don't use the src
attribute.
Hope that helps! :)