I am attempting to speed up the responsiveness of my micro-controller based web pages by loading the JavaScript after the page fully loads. I found this method in many places:
if (window.addEventListener)
window.addEventListener("load", doAfterPageLoad, false);
else if (window.attachEvent)
window.attachEvent("onload", doAfterPageLoad);
else window.onload = doAfterPageLoad;
The events certainly happen the way I wanted them to, but resources, specifically jQuery, do not appear to be accessible after loaded. This is an examplar script demonstrating what I am facing:
<script type="text/javascript">
function loadPageData() {
console.log("DEBUG: Entering: " + arguments.callee.name);
// Do stuff requiring jQuery here
console.log("DEBUG: Exiting: " + arguments.callee.name);
}
function loadJS() {
console.log("DEBUG: Entering: " + arguments.callee.name);
var jq = document.createElement("script");
jq.type = "text/javascript";
jq.crossOrigin = "anonymous";
jq.integrity = "sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=";
jq.src = "https://code.jquery.com/jquery-3.4.1.min.js";
document.body.appendChild(jq);
var pop = document.createElement("script");
pop.type = "text/javascript";
pop.crossOrigin = "anonymous";
pop.integrity = "sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1";
pop.src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js";
document.body.appendChild(pop);
var bs = document.createElement("script");
bs.type = "text/javascript";
bs.crossOrigin = "anonymous";
bs.integrity = "sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM";
bs.src = "https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js";
document.body.appendChild(bs);
console.log("DEBUG: Leaving: " + arguments.callee.name);
}
function doAfterPageLoad() { // Load the page's JS elements
console.log("DEBUG: Entering: " + arguments.callee.name);
loadJS(); // Load external JS
if(window.jQuery) {
loadPageData(); // Load once on page load
} else {
console.log("DEBUG: jQuery not loaded.");
}
console.log("DEBUG: Leaving: " + arguments.callee.name);
}
// Attach the event after the page loads
window.addEventListener("load", doAfterPageLoad, false);
</script>
From this I get the following console log:
DEBUG: Entering: doAfterPageLoad
DEBUG: Entering: loadJS
DEBUG: Leaving: loadJS
DEBUG: jQuery not loaded.
DEBUG: Leaving: doAfterPageLoad
DEBUG: Entering: loadJS
DEBUG: Leaving: loadJS
DEBUG: jQuery not loaded.
DEBUG: Leaving: doAfterPageLoad
So, jQuery is not available to the rest of the script, specifically loadPageData()
.
I suspect it's some sort of scope issue, but so far I've not been able to crack this particular nut.