延迟加载脚本来加速网页 - jQuery lazyloadscripts

延迟加载脚本来加速网页 - jQuery lazyloadscripts

版本:

浏览量:70

最后更新:2021-09-12

应用标签:MAC 软件Jquery插件

推荐指数:

详细信息

A lightweight yet useful jQuery plugin for lazy loading a single or multiple scripts to speed Up your websites and improve the user experience.

Useful for lazy loading heavy JavaScript libraries (such as Google Maps, Disqus Comments, etc) to increase your page speed.

The biggest difference between lazyloadscripts and defer/async is that the plugin delays the loading of any scripts until they're scrolled into view.

How to use it:

1. Insert the minified version of the jQuery lazyloadscripts plugin after jQuery.

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha384-tsQFqpEReu7ZLhBV2VZlAu7zcOV+rXbYlF2cqB8txI/8aZajjp4Bqd+V6D5IgvKT"
        crossorigin="anonymous">
</script>
<script src="dist/jquery.lazyloadscripts.min.js"></script>

2. Specify the script URL to defer loading until the container 'example' is scrolled into the viewport.

<div id="example"
     data-lazy-load-scripts="js.js">
</div>

3. You can also specify an array of script URLs to defer loading.

<div id="example"
     data-lazy-load-scripts="["1.js", "2.js", "3.js"]">
</div>

4. Attach the plugin to the container element.

$('#example').lazyLoadScripts();

5. Specify the distance from the top of the webpage the scripts will start loading. Default: 0.

$('#example').lazyLoadScripts({
  offset: 100
});

6. Get the DOM element, JavaScript path and loading stat using the onWatch callback.

$('#example').lazyLoadScripts({
  onWatch: function(elements)
  {
    console.log(elements)
    /* return object:
    {
      0: {
        elem: $(section),
        inDom: false || true,
        scriptSrc: SCRIPT_URL
      },
      ...
    }
    */
  }
});

7. Execute a function when a request is successfully executed

$('#example').lazyLoadScripts({
  onSuccess: function() {}
});

8. 加载所有脚本后执行一个函数。

$('#example').lazyLoadScripts({
  onAllDone: function() {}
});

9. 发生错误时执行函数。

$('#example').lazyLoadScripts({
  onFail: function(error) {}
});

变更日志:

2020-04-10

  • 添加 `onAllDone` 和 `onFail` - 回调

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。