load scripts asynchronously

前端 未结 19 1312
粉色の甜心
粉色の甜心 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

提交回复
热议问题