Skip to content
TURNKEYGNU / LINUX
AppsDocumentationForumBlogScreenshotsGitHubTurnKey Hub
文English
EnglishDeutschEspañol日本語Portuguêsहिंदी中文
Home/Blog/load any external javascript file asynchronously

From the project

load any external javascript file asynchronously

By Liraz SiriOctober 13, 20141 min read

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.

Keep exploring

Find your next server

Find ready-to-run apps for the job you need to do.

Explore the app library
TURNKEYGNU / LINUX

Secure self-hosting without starting from scratch

Explore TurnKey
AboutDocumentationForumFAQBlogGitHub
Free and open sourceSecure by defaultReady to deploy