loadScript,非阻塞 JavaScript 加载库

本文介绍了如何利用jQuery.loadScript实现JavaScript的非阻塞加载,以提高网页性能。通过引用GitHub上的相关库,如jQuery.loadscript.js,以及HTMLScriptElement属性,可以实现延迟加载和并行加载js。同时,文章提到了其他类似解决方案,如when.js和Yahoo的LazyLoad,后者在压缩后仅有1.5KB,并提供了详细的使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在看高性能JavaScript书的时候看到一个写法,当然现在很多库了(when.js等),然后取github上收了下,算是它的一个封装。

地址:https://github.com/marcbuils/jquery.loadscript/blob/master/jquery.loadscript.js

/**
 * PluginAutoLoad: Load your plugins on html DOM without javascript code.
 * http://marcbuils.github.com/jquery.pluginautoload/
 * https://github.com/leiming/jquery.loadscript
 *
 * Par Marc Buils ( marc.buils@marcbuils.fr )
 * Lei Ming ( poetcoders@gmail.com )
 * Sous licence LGPL v3 (http://www.gnu.org/licenses/lgpl-3.0.txt)
 *
 * v0.1.1 - 09/16/2015:
 * First release
 *
 * v0.1.2 - 12/09/2015;
 * Fix lazyLoad bug
 */

$(function () {
  // lazyload script
  // ref: http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
  // https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement
  var _loadScript = function (url, params, callback) {

    var script = document.createElement("script");
    script.type = "text/javascript";

    if (script.readyState) { //IE
      script.onreadystatechange = function () {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function () {
        callback();
      };
    }

    var scriptsProperties = [
      'type', 'src', 'htmlFor', 'event', 'charset', 'async', 'defer', 'crossOrigin', 'text', 'onerror'
    ];

    if (typeof params === 'object' && !$.isEmptyObject(params)) {
      for (var key in params) {
        if (params.hasOwnProperty(key) && $.inArray(key, scriptsProperties)) {
          script[key] = params[key];
        }
      }
    }

    document.getElementsByTagName(params['lazyLoad'] ? 'body' : 'head')[0].appendChild(script);
    script.src = url;
  };

  $.loadScript = function (p_url, p_params, p_callback) {

    // Handle p_params is exist
    if (arguments.length === 2 && typeof arguments[1] === 'function') {
      p_callback = arguments[1];
      p_params = {}
    }

    p_params = p_params || {};

    var _return = $.Deferred();

    // Call callback if necessary
    if (typeof( p_callback ) === 'function') {
      _return.done(function () {
        p_callback();
      });
    }

    // Load javascript file
    _loadScript(p_url, p_params, function () {
      _return.resolve();
    });

    return _return.promise();
  };
})
具体看: https://github.com/marcbuils/jquery.loadscript

关于script标签属性,可以看看这里HTMLScriptElementhttps://developer.mozilla.org/zh-CN/docs/Web/API
另3篇:

第一个loadScript可以看看 https://github.com/zynga/loadScript/blob/master/loadScript.js

第二个是雅虎的LazyLoadhttps://github.com/rgrove/lazyload/blob/master/lazyload.js

LazyLoad 是一个更强大的 loadScript()函数。 LazyLoad 精缩之后只有大
约 1.5KB(精缩,而不是用 gzip 压缩的)。用法举例如下:

<script type="text/javascript" src="lazyload-min.js"></script>
<script type="text/javascript">
    LazyLoad.js("the-rest.js", function () {
        Application.init();
    });
</script>
// Load a single JavaScript file and execute a callback when it finishes.
LazyLoad.js('http://example.com/foo.js', function () {
  alert('foo.js has been loaded');
});

// Load multiple JS files and execute a callback when they've all finished.
LazyLoad.js(['foo.js', 'bar.js', 'baz.js'], function () {
  alert('all files have been loaded');
});

// Load a CSS file and pass an argument to the callback function.
LazyLoad.css('foo.css', function (arg) {
  alert(arg);
}, 'foo.css has been loaded');

// Load a CSS file and execute the callback in a different scope.
LazyLoad.css('foo.css', function () {
  alert(this.foo); // displays 'bar'
}, null, {foo: 'bar'});


第三个非阻塞 JavaScript 加载库是 LABjs:https://github.com/getify/LABjs此库对加载过程进行更精细的控制,并尝试并行下载尽可能多的代码。具体可以看

它的官网(http://labjs.com/documentation.php)或者github。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值