I work with an advertising company, where we tag certain pages to track activity. A client of mine wants to fire off a javascript tag to track activity AFTER the page has fi
For a Progressive Web App I wrote a script to easily load javascript files async on demand. Scripts are only loaded once. So you can call loadScript as often as you want for the same file. It wouldn't be loaded twice. This script requires JQuery to work.
For example:
loadScript("js/myscript.js").then(function(){
// Do whatever you want to do after script load
});
or when used in an async function:
await loadScript("js/myscript.js");
// Do whatever you want to do after script load
In your case you may execute this after document ready:
$(document).ready(async function() {
await loadScript("js/myscript.js");
// Do whatever you want to do after script is ready
});
Function for loadScript:
function loadScript(src) {
return new Promise(function (resolve, reject) {
if ($("script[src='" + src + "']").length === 0) {
var script = document.createElement('script');
script.onload = function () {
resolve();
};
script.onerror = function () {
reject();
};
script.src = src;
document.body.appendChild(script);
} else {
resolve();
}
});
}
Benefit of this way: