Created
September 20, 2023 16:49
-
-
Save ahmu83/98ca7ae6bf41165846661390508a5fcf to your computer and use it in GitHub Desktop.
Dynamic Script Enqueuing for the DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Enqueue scripts dynamically into DOM. | |
* Example usage | |
* | |
* enqueueScript({ | |
* 'html2canvas': { | |
* id: 'html2canvas', | |
* url: 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js', | |
* onload: () => { | |
* // code | |
* }, | |
* }, | |
* 'FileSaver': { | |
* id: 'FileSaver', | |
* url: 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js', | |
* }, | |
* }, () => { | |
* | |
* // code | |
* | |
* }); | |
* | |
* @param Object scripts [Scripts object] | |
* @param Boolean callback [Callback function to call after all the scripts are loaded] | |
* @return Void | |
*/ | |
function enqueueScript(scripts, callback = false) { | |
var key, key2, script, scriptId, scriptUrl, scriptElem, scriptExists, scriptsLength, scriptsLoaded, scriptAttributes; | |
scriptsLoaded = scriptsLength = 0; | |
for (key in scripts) { | |
scriptsLength++; | |
} | |
for (key in scripts) { | |
if (typeof scripts[key].id === 'undefined') scripts[key].id = key; | |
script = scripts[key]; | |
scriptId = script.id; | |
scriptUrl = script.url; | |
scriptAttributes = typeof script.attributes === 'undefined' ? {} : script.attributes; | |
scriptExists = document.querySelector('script#' + scriptId); | |
if ( !scriptExists ) { | |
scriptElem = document.createElement('script'); | |
scriptElem.src = scriptUrl; | |
scriptElem.id = scriptId; | |
for (key2 in scriptAttributes) { | |
scriptElem[key2] = scriptAttributes[key2]; | |
} | |
if (document.head) { | |
document.head.appendChild(scriptElem); | |
} else if (document.body) { | |
document.body.appendChild(scriptElem); | |
} else { | |
return; // no place to add the script | |
} | |
scriptElem.onload = function(script) { | |
script = scripts[script.target.getAttribute('id')]; | |
scriptsLoaded++; | |
if ( typeof script.onload === 'function' ) { | |
script.onload(); | |
} | |
} | |
/** | |
* Callback function to run after script is loaded | |
*/ | |
} else if ( scriptExists && typeof script.onload === 'function' ) { | |
script.onload(); | |
scriptsLoaded++; | |
} else if ( scriptExists && typeof script.onload === 'undefined' ) { | |
scriptsLoaded++; | |
} | |
} | |
if ( typeof callback === 'function' ) { | |
var interval = setInterval(function() { | |
if (scriptsLength === scriptsLoaded) { | |
callback(); | |
clearInterval(interval); | |
} | |
}, 100); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment