
Although it is usually easier to explicitly add references to all your JavaScript file dependencies in the host web page (head section), sometimes this isn’t possible and the dependencies need to be programmatically loaded at runtime.
For example, if you are developing a piece of re-usable code that is only enabled sometimes (under certain conditions) then it may be better to conditionally load the script at runtime from another JS block instead of bloating the page load time with all script file contingencies.
The simplest way of doing this if you don’t mind relying on a JS Framework is to use jQuery. This has a handy ‘getScript’ function for just this purpose.
// Old-skool jQuery way of loading the script.
$.getScript('https://someCDN/apis/someapi.js', function (data, textStatus, jqxhr) {
// Do something with someapi now it has been loaded.
});
// More recent approach using the 'modern' callback handlers.
$.getScript('https://someCDN/apis/someapi.js')
.done(function (script, textStatus, jqxhr) {
// Do something with someapi now it has been loaded.
})
.fail(function (jqxhr, settings, exception) {
console.error('Failed to load someapi.js script');
});
Code language: JavaScript (javascript)
Simple, isn’t it?!
But, what if the script you want to dynamically load is jQuery itself? Well, that’s not too difficult either. Something like this in plain JavaScript would work just fine, but you’d need to have some supervisory code in place to monitor for the page having loaded before attempting to access the ‘document’ object…
// We need to wait for the document to have finished loading before adding scripts.
document.onreadystatechange = function () {
if (document.readyState === 'complete') {
// document is ready.
var myScript = document.createElement('script');
myScript.onload = function () {
// Do something with someapi now it has been loaded.
};
myScript.src =
'https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js';
document.head.appendChild(myScript);
}
}
Code language: JavaScript (javascript)