Module for Loading Scripts Asynchronously


Thu Oct 19 2023 06:27:29 GMT+0000 (Coordinated Universal Time)

Saved by @daemondevin #javascript #module #async #script

 *    @module
 *    @author daemon.devin <>
 *    @param {String}   file - The path of the file you want to load.
 *    @param {Function} callback (optional) - Called after script load.
var loader = loader || (Function() {
    return {
    	load: function(file, callback) {

            var script = document.createElement('script');
            script.src = file, script.async = true;
  			// If defined, execute the callback after checking 
  			// if the script has been successfully loaded.
            if (callback !== undefined) {
            	// IE calls `script.onreadystatechange()` continuously
            	// as the script loads. Use `script.onreadystatechange()`
            	// to check if the script has finished loading.
	        script.onreadystatechange = function() {
	            // When the script finishes loading, IE sets 
	            // `script.readyState` to either 'loaded' or 'complete'.
	            if (script.readyState === 'loaded' ||
	                script.readyState === 'complete') {
                  	// Set `onreadystatechange()` to null to prevent 
                  	// it from firing again.
	                script.onreadystatechange = null;
	                // Execute the callback.
	                callback (file );
	        // The following is one of the reasons IE is infereor
            // to all modern browsers.
	        script.onload = function () {
	            callback ( file );
  			// Add the loaded script to the end of the document 
  			// so it won't hinder the rest of the page from loading.

####Description This module uses the `script.async` attribute _(see line 30)_, which tells the browser to load the script asynchronously. Most modern browsers support this async functionality, but those that don't will simply overlook it without causing problems. Moreover, older versions of IE, Webkit, and Firefox 4+ that don't support the async attribute will still load scripts asynchronously if you use this module. The reason is this: if you use javascript to insert a script element into the DOM, those browsers will load it asynchronously. Only Opera and pre-Firefox 4 don't do this.