Skip to content

Instantly share code, notes, and snippets.

@felipebn
Last active September 27, 2023 01:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipebn/61d978d2884b7e57fbea8d5110961cc9 to your computer and use it in GitHub Desktop.
Save felipebn/61d978d2884b7e57fbea8d5110961cc9 to your computer and use it in GitHub Desktop.
3rdparty.js script loading callback
console.log("3rdparty script START");
// this should be called from consumer page
window.customFunction = function () {
console.log("custom function called!!!!");
};
console.log("3rdparty script END");
<!DOCTYPE html>
<html>
<head>
<title>After JS load callback example</title>
<meta charset="UTF-8" />
<script src="./index.js"></script>
</head>
<body>
<div id="app">
Page test, check console logs!
</div>
<script src="./3rdparty.js" defer="true"></script>
</body>
</html>
console.log("index.js script START");
const checkScript = () => {
const scriptTag = document.querySelectorAll("script[src$='3rdparty.js']")[0];
if(scriptTag) {
console.log("[index.js] 3rd party script element found:", scriptTag);
scriptTag.addEventListener("load", () => {
console.log("[index.js] 3rdparty.js loaded ===>>>");
window.customFunction && window.customFunction();
});
}else{
console.error('[index.js] 3rdparty.js not there yet');
}
};
// this only fires after the HTML was parsed, but before the additional scripts finish loading
// https://developer.mozilla.org/en-US/docs/Web/API/Document/readyState
document.addEventListener("readystatechange", (event) => {
if(document.readyState === 'interactive') {
checkScript();
}
});
console.log("index.js script END");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment