简体   繁体   中英

Async JS loading in head

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 (dont 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

Thanks

Put 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.com/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 compatible). 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: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM