Lazy Load Scripts To Speed Up Webpages - jQuery lazyloadscripts

File Size: 33.4 KB
Views Total: 2039
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Lazy Load Scripts To Speed Up Webpages - jQuery lazyloadscripts

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. Execute a function when all scripts are loaded.

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

9. Execute a function when an error occurs.

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

Changelog:

2020-04-10

  • Add `onAllDone` and `onFail`- callbacks

This awesome jQuery plugin is developed by pgmlde. For more Advanced Usages, please check the demo page or visit the official website.