Dynamically Load JS and CSS and Their Dependencies Using jQuery - loader.js

File Size: 9.48 KB
Views Total: 884
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Dynamically Load JS and CSS and Their Dependencies Using jQuery - loader.js

loader.js is a lightweight asset loader jQuery plugin that allows you to dynamically load JavaScript and Stylesheet files with their dependencies in the document.

The goal of the plugin is to simplify the task of adding CSS and JavaScript files, with dependencies, and to make it easier for you to control when these are loaded into the page.

How to use it:

1. To begin with, include the loader.js library after jQuery.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/jquery.loader.js"></script>

2. Define an array of JavaScript (and/or CSS) files with their dependencies as follows:

// JavaScript
const jsList = [
      {
        name: 'main',
        src: 'js/main.js',
        dep: [
          'sub-1',
          'sub-2'
        ]
      },
      {
        name: 'sub-1',
        src: 'js/sub1.js',
        dep: [
          'sub-3'
        ]
      },
      {
        name: 'sub-2',
        src: 'js/sub2.js',
        dep: []
      },
      {
        name: 'sub-3',
        src: 'js/sub3.js',
        dep: []
      }
],

// CSS
const cssList = [
      {
        name: 'main',
        src: 'css/main.css',
        dep: [
          'sub-1',
          'sub-2'
        ]
      },
      {
        name: 'sub-1',
        src: 'css/sub1.css',
        dep: [
          'sub-3'
        ]
      },
      {
        name: 'sub-2',
        src: 'css/sub2.css',
        dep: []
      },
      {
        name: 'sub-3',
        src: 'css/sub3.css',
        dep: []
      }
],

3. Available plugin options.

$.loader ({
  js: jsList,
  css: cssList,
  // enable browser cache
  cache: false,
  // 0 will disable retry.
  retryLimit: 3,
  // timeout in miliseconds to wait for script load
  // 0 will disable timeout
  timeout: 0,
});

4. Available callback functions.

$.loader ({
  js: jsList,
  css: cssList,
  onupdate: function (script){
    // on update
  },
  onrefresh: function (loaded, total, percentage){
    // on refresh
  },
  onfinish: function (total){
    // on finish
  },
  onloadfail: function (error){
    // on load fail
  },
  onsuccess: function (name){
    // on success
  },
  onfail: function (name){
    // on fail
  }
});

Changelog:

2024-02-20

  • Added nonce attribute support to be used with CSP.

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