load scripts asynchronously

前端 未结 19 1023
粉色の甜心
粉色の甜心 2020-11-22 12:01

I am using several plugins, custom widgets and some other libraries from JQuery. as a result I have several .js and .css files. I need to create a loader for my site because

相关标签:
19条回答
  • 2020-11-22 12:38

    Here is my custom solution to eliminate render-blocking JavaScript:

    // put all your JS files here, in correct order
    const libs = {
      "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
      "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
      "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
      "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
    }
    const loadedLibs = {}
    let counter = 0
    
    const loadAsync = function(lib) {
      var http = new XMLHttpRequest()
      http.open("GET", libs[lib], true)
      http.onload = () => {
        loadedLibs[lib] = http.responseText
        if (++counter == Object.keys(libs).length) startScripts()
      }
      http.send()
    }
    
    const startScripts = function() {
      for (var lib in libs) eval(loadedLibs[lib])
      console.log("allLoaded")
    }
    
    for (var lib in libs) loadAsync(lib)
    

    In short, it loads all your scripts asynchronously, and then executes them consequently.

    Github repo: https://github.com/mudroljub/js-async-loader

    0 讨论(0)
  • 2020-11-22 12:39

    I would complete zzzzBov's answer with a check for the presence of callback and allow passing of arguments:

        function loadScript(src, callback, args) {
          var s, r, t;
          r = false;
          s = document.createElement('script');
          s.type = 'text/javascript';
          s.src = src;
          if (typeof(callback) === 'function') {
            s.onload = s.onreadystatechange = function() {
              if (!r && (!this.readyState || this.readyState === 'complete')) {
                r = true;
                callback.apply(args);
              }
            };
          };
          t = document.getElementsByTagName('script')[0];
          t.parent.insertBefore(s, t);
        }
    
    0 讨论(0)
  • 2020-11-22 12:41

    Check out this https://github.com/stephen-lazarionok/async-resource-loader. It has an example that shows how to load JS, CSS and multiple files with one shot.

    0 讨论(0)
  • 2020-11-22 12:43

    Example from google

    <script type="text/javascript">
      (function() {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js?onload=onLoadCallback';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
      })();
    </script>
    
    0 讨论(0)
  • 2020-11-22 12:43

    I would suggest you take a look at Modernizr. Its a small light weight library that you can asynchronously load your javascript with features that allow you to check if the file is loaded and execute the script in the other you specify.

    Here is an example of loading jquery:

    Modernizr.load([
      {
        load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js',
        complete: function () {
          if ( !window.jQuery ) {
                Modernizr.load('js/libs/jquery-1.6.1.min.js');
          }
        }
      },
      {
        // This will wait for the fallback to load and
        // execute if it needs to.
        load: 'needs-jQuery.js'
      }
    ]);
    
    0 讨论(0)
  • 2020-11-22 12:44

    HTML5's new 'async' attribute is supposed to do the trick. 'defer' is also supported in most browsers if you care about IE.

    async - The HTML

    <script async src="siteScript.js" onload="myInit()"></script>
    

    defer - The HTML

    <script defer src="siteScript.js" onload="myInit()"></script>
    

    While analyzing the new adsense ad unit code I noticed the attribute and a search lead me here: http://davidwalsh.name/html5-async

    0 讨论(0)
提交回复
热议问题