延迟加载javascript

延迟加载javascript

本文介绍了延迟加载javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the basic difference between this 3 ways for lazy loading js or ondemand loading and why?

脚本1:

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

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!'));
    });
};

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])
};

推荐答案

  1. 使用ajax加载脚本.更具体地说,它使用XHR加载一些js并将其提供给浏览器.没有阻止完成.它仍然会强制执行相同的原始策略.
  2. 通过创建<script/>元素来修改标头以注入新的.js文件.这也不会阻止浏览器加载页面.
  3. 与#2相同,但似乎支持一系列脚本.它还将async设置为true,这不会导致阻塞. for循环更加令人困惑,因为它创建了更多的匿名方法.
  1. Uses ajax to load the script. More specifically it uses XHR to load some js and have it available to the browser. No blocking is done. It does still enforce the same origin policy.
  2. Modifies the header to inject a new .js file by creating <script/> element. This also doesn't block the browser on page load.
  3. Does the same thing as #2 but it seems to support an array of scripts. It also sets async to true which causes no blocking. The for loop is just more confusing because it creates a lot more anonymous methods.

这篇关于延迟加载javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 15:14