Lazy Load Scripts To Speed Up Webpages - jQuery lazyloadscripts

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

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
      },
      ...
    }
    */
  }
});

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