2

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 2

5

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/

Sign up to request clarification or add additional context in comments.

2 Comments

I am exactly doing this but inside HEAD. Do you recommend it doing above head? I dont think that will be valid HTML and will it work across browsers, asynchronously?
i just understood what you are trying to do, updated the answer for that
3

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! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.