Grow your CSS skills. Land your dream job.

Last updated on:

Async Script Loader with Callback

var Loader = function () { }
Loader.prototype = {
    require: function (scripts, callback) {
        this.loadCount      = 0;
        this.totalRequired  = scripts.length;
        this.callback       = callback;

        for (var i = 0; i < scripts.length; i++) {
            this.writeScript(scripts[i]);
        }
    },
    loaded: function (evt) {
        this.loadCount++;

        if (this.loadCount == this.totalRequired && typeof this.callback == 'function') this.callback.call();
    },
    writeScript: function (src) {
        var self = this;
        var s = document.createElement('script');
        s.type = "text/javascript";
        s.async = true;
        s.src = src;
        s.addEventListener('load', function (e) { self.loaded(e); }, false);
        var head = document.getElementsByTagName('head')[0];
        head.appendChild(s);
    }
}

Usage

var l = new Loader();
l.require([
    "example-script-1.js",
    "example-script-2.js"], 
    function() {
        // Callback
        console.log('All Scripts Loaded');
    });

Reference URL

Comments

  1. Permalink to comment#

    i request you to provide these code with demo… will help us a lot..

    thank you for your help.

  2. Thanks I just borrowed the writeScript method and trimmed it down a bit. Surprising how many times I do async loading and always forget the exact way to create the script element etc. Thanks!

  3. Maybe good to mention that “addEventListener” is not supported in IE8 or lower.
    They use “attachEvent”. You can support IE like this:

    if(s.addEventListener) {
    s.addEventListener(‘load’, function (e) { self.loaded(e); }, false);
    } else if(s.attachEvent) {
    s.attachEvent(‘load’, function (e) { self.loaded(e); }
    }

    Or if you are using jQuery you can use:

    jQuery(s).load(function(e) { self.loaded(e); });

    see: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener)”

    • jockchou
      Permalink to comment#

      But script tag have not ‘load’ event. you should use ‘onreadystatechange’ to listene the scripts load.
      if (s.addEventListener) {
      s.addEventListner(‘load’, function(e) {
      //callback here
      }, false);
      } else {
      s.onreadystatechange = function() {
      if (s.readyState in {loaded: 1, complete: 1}) {
      //callback here
      }
      };
      }

      //some code

      function loadScript(url, callback){
      var script = document.createElement(“script”);
      script.type = “text/javascript”;
      script.charset = “utf8″;
      if (script.readyState) {//IE
      script.onreadystatechange = function() {
      if (script.readyState == ‘loaded’ || script.readyState == ‘complete’) {
      script.onreadystatechange = null;
      if (typeof callback === ‘function’) {
      callback();
      }
      }
      };
      } else {//other browers
      script.onload = function() {
      script.onload = null;
      if (typeof callback === ‘function’) {
      callback();
      }
      };
      }
      script.src = url;
      document.getElementsByTagName(“head”)[0].appendChild(script);
      }

  4. @jockchou : your comment about using onreadystatechange instead as the trigger for the callback helped me get this working in IE8. Thanks!

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".