Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to load javascript files asynchronously

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 174
    Comment on it

    Hello all,

    Working with HTML and JavaScript we usually keep our JavaScript code in separate files to keep our code organized and manageable.

    If we are using various plugins in our website which has lots of JavaScript files with it, in that case it takes quite a lot of time to load those files resulting into slowing the speed of your website.

    To avoid such problems we can load our required JavaScript files asynchronously which also known as lazy loading of scripts, and there are various ways of doing that, Some of them are listed bellow :

    1. In HTML5 we can add async attribute to the link of the JavaScript file. Ex.

      <script async src="http://findnerd.com//jsFile.js"></script> 
      

    2. We can also create a function that will contain the logic to load and include your JavaScript files asynchronously, and the function will be like following :

      function loadFile() {
          var scriptFile = document.createElement('script'); 
          scriptFile .src = "//jsFile.js"; // set the src attribute to variable "scriptFile"
          script.type = 'text/javascript'; 
          scriptFile.async = true; // the HTML5 async attribute
          var head = document.getElementsByTagName('head')[0];
          head.appendChild(scriptFile);
      }
      

      and now in onload function of body tag we can call this function and in this way the file will be loaded asynchronously.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: