Web Designing Tutorials

How to Load External JavaScript Asynchronously or Dynamically

Pinterest LinkedIn Tumblr
JavaScript makes easier to manipulate websites, nowadays most of the browsers supporting JavaScript codes. When the HTML parser encounters an element. It runs the script before it can be parsing and rendering the document. It is not much problem for inline scripts but if the script source code is in an external file specified with an src attribute, the portions of the document that follow the Script will not appear in the browser until your browser load external JavaScript has been downloaded and executed. This makes loading the website much slower, which makes a bad user experience for your website. As a result, your website may not be indexing your website by the search engines.

This Synchronous or blocking script execution is the default only. The <script> tag can have deferred and async attributes, which cause scripts to be executed differently. This makes your website loading much faster than before and appears contents of your site by loading at first.

Read Also: How to Write Conditional Statements in JavaScript?

How to Load External JavaScript Asynchronously

You can load external Javascript asynchronously either using async or defer attributes or loading external scripts when document finishes loading.

Using async or defer attributes

Since the defer and async attributes are ways of telling the browser that the linked script does not use the document.write() method. It won’t be generating document content. So the browser can continue to parse and render the document while downloading the script. You can use async or defer attributes as the following.

<script defer src="deferred.js"></script> 
<script async src="async.js"></script>

The defer attribute causes the browser to defer execution of the script until after the document has been loaded and parsed and is ready to be manipulated. The async attribute causes the browser to run the script as soon as possible but not to block document parsing while the script is being downloaded. If a <script> tag has both attributes, a browser that supports both will honor the async attribute and ignore the defer attribute. Deferred scripts run in the order in which they appear in the document, while async scripts run as they load, which means that they may execute out of order.

Here is an example of the async script uses in this blog for the IntenseDebate comments script source.

<script async='async' expr:src='data:post.commentSrc' type='text/javascript'/>

Read Also: What are the Different Ways to Redirect Page in JavaScript?

Loading when document finishes loading 

You can load and execute scripts asynchronously by using setTimeout(), addEventListner(), and attachEvent(). Most objects that can be event targets have a method named addEventListner(), which allows the registration of multiple listeners.

window.addEventListner("load", function(){.....},false);
request.addEventListner("readystatechange", function(){......},false);

The first argument to this function is the name of the event. For IE8 and earlier, you must use a similar method, named attachEvent().

window.attachevent("onload", function() {.....});

Here is an example that defines an onLoad() function that registers a function to be run when the document finishes loading. If the document has already loaded, run it asynchronously.

function onLoad(f){
elseif (window.addEventListner)
elseif (window.attachEvent)

In the above script window.attachEvent is used for IE8 and earlier. onLoad.loaded=false; sets a flag that indicates the document is not loaded yet and onLoad(function(){onLoad.loaded=true;}); register a function to set the flag when the document does load.

Read Also: How to Add Multiple Slideshows on One Page Using Javascript

How to Load External JavaScript dynamically

You can load and execute scripts asynchronously, even in browsers that do not support the async attribute, by dynamically creating a <script> element and inserting it into the document. Here is an example of how to load scripts dynamically.

function loadasync(url){
var head=document.getElementByTagName("head")[0]; 
var s=document.createElement("script"); 

This loadsaync() function finds the <head> tag and attach <script> tag below the opening of head tag and loads scripts dynamically. Scripts that are neither included inline within the web page or referenced statically from the web page are loaded into the document and become part of the running JavaScript program.

You can use the following method to execute loadsync() function when the document finished loading.

function loadasync(){ ..................}

Here is an example of loading JavaScript asynchronously by loading scripts dynamically used in this blog for external scripts from Infolinks ads.

<div style='display:none'>  <div id='adsource-0'>
<script type='text/javascript'>
var infolinks_pid = 9993182;
var infolinks_wsid = 1;
    <script language='javascript' src='https://resources.infolinks.com/js/infolinks_main.js' type='text/javascript'/>
<script type='text/javascript'>
    source = document.getElementById("adsource-0");
    placeholder = document.getElementById("ad-0");

I have placed this code at the bottom of HTML codes, i.e. just before </body> tag and have placed the following code where I want to display ads.

<div id="ad-0" align="center"></div>

Read Next: How to Validate an HTML Form Using JavaScript?


Shuseel Baral is a web programmer and the founder of InfoTechSite has over 8 years of experience in software development, internet, SEO, blogging and marketing digital products and services is passionate about exceeding your expectations.

Comments are closed.