Last active
September 27, 2023 01:37
-
-
Save felipebn/61d978d2884b7e57fbea8d5110961cc9 to your computer and use it in GitHub Desktop.
3rdparty.js script loading callback
This file contains hidden or 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
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"); |
This file contains hidden or 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
<!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> |
This file contains hidden or 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
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