load any external javascript file asynchronously

Sticking <script></script> tags referring an external resource in the middle of your HTML code will hang the loading of your page while your browser gets the missing script.

On the TurnKey website, this was a problem with the loading of the AddToAny sharing script, and the quantcast tag which I have since removed. There were also a couple of custom scripts that slowed down the site.

The solution is generic and simple. Use this code to load your Javascript asynchronously:


<script type="text/javascript">

(function() {
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.async = true;
    s.src = 'http://yourdomain.com/script.js';
    var x = document.getElementsByTagName('script')[0];
    x.parentNode.insertBefore(s, x);
})();

</script>

Instead of loading it synchronously:

<script type="text/javascript" src="http://yourdomain.com/script.js"></script>

One thing to consider is that asynchronous loaded Javascript will not block jQuery's document.ready handlers. Synchronous scripts will. If your jQuery code depends on a plugin (e.g., the simple modal dialog) it may be better to load it synchronously instead.

You can get future posts delivered by email or good old-fashioned RSS.
TurnKey also has a presence on Google+, Twitter and Facebook.

Comments

Thomas Jones's picture

Interesting idea - I guess some things such as cookie compliance cookie scripts could be best loaded a lot later to improve upon user-experience beforehand.  domestic cleaner exeter

Ben's picture

I tested it and it really works. Thanks for sharing your knowledge :)

kalautau.com's picture

Great, This script work for me. but how about manipulation many javascript? please give me example. because in my blog have any java script and jquery

http://kalautau.com

Imran Khalid's picture

Hi

Thanx for sharing this idea, but whats about more than one scripts, how can we add all of them like this?

can you explain with example?

David Taubmann's picture

I love it, and am using it in a webapp proyect. Works great. 

I honestly believe there are solutions for this already implemented in alternatives like Angular and such, but in this moment I can't take some learning curve to learn another new thing.

My comment is turning into a question from here... 

May it be possible to promesify (thenify) this using something like addEventListener("load",resolve) ?

I'm going to try to build such just now, but would appreciate if you have already done such a solution.

Keep the good work!

David from Mexico

Jobs Assam's picture

I have implemented in my website and it worked but i want to ask you is there any code if i have many script. Please check my website if i have implemented in my website correctly or not www.jobsassam.com . Also i want to ask you is there any code of lazy loading of images.

Pages

Post new comment