当前位置: 首页 > 工具软件 > loadScript > 使用案例 >

loadScript,非阻塞 JavaScript 加载库

吉毅
2023-12-01

在看高性能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。





 类似资料: