懒加载javascript

pau*_*aul 7 javascript jquery

延迟加载js或按需加载这三种方式之间的基本区别是什么?为什么?

脚本1:

$.getScript = function(url, callback, cache){
   $.ajax({
      type: "GET",
      url: url,
      success: callback,
      dataType: "script",
      cache: cache
   });
};
Run Code Online (Sandbox Code Playgroud)

SCRIPT2:

function require(file, callback) {
    var script = document.getElementsByTagName('script')[0],
        newjs = document.createElement('script');

    // IE
    newjs.onreadystatechange = function () {
        if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
            callback();
        }
    };

    // others
    newjs.onload = function () {
        callback();
    };

    newjs.src = file;
    script.parentNode.insertBefore(newjs, script);
}

document.getElementById('id').onclick = function () {
    require('ondemand.js', function () {
        extraFunction('loaded from the parent page');
        document.body.appendChild(document.createTextNode('done!'));
    });
};
Run Code Online (Sandbox Code Playgroud)

script3:

$L = function (c, d) {
    for (var b = c.length, e = b, f = function () {
            if (!(this.readyState
                    && this.readyState !== "complete"
                    && this.readyState !== "loaded")) {
                this.onload = this.onreadystatechange = null;
                --e || d()
            }
        }, g = document.getElementsByTagName("head")[0], i = function (h) {
            var a = document.createElement("script");
            a.async = true;
            a.src = h;
            a.onload = a.onreadystatechange = f;
            g.appendChild(a)
        }; b;) i(c[--b])
};
Run Code Online (Sandbox Code Playgroud)

Ami*_*far 7

  1. 使用ajax加载脚本.更具体地说,它使用XHR加载一些js并将其提供给浏览器.没有阻止.它仍然执行相同的原始政策.
  2. 修改标题以通过创建<script/>元素注入新的.js文件.这也不会阻止浏览器加载页面.
  3. 和#2一样,但它似乎支持一系列脚本.它还将async设置为true,这不会导致阻塞.for循环更令人困惑,因为它创建了更多的匿名方法.