Created
April 11, 2019 15:21
-
-
Save gtempesta/a5529bcece20f5b28fc84fff1d51a6c9 to your computer and use it in GitHub Desktop.
Run some code only after a script has been executed
This file contains 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
// createdObj is an object created by the script | |
// setup that should run after the script has been executed | |
var setup = function(){ | |
console.log('the script is on the page and did execute'); | |
console.log(typeof createdObj, 'does it exist?'); // -> function | |
}; | |
// attach the script to the page | |
var script = document.createElement("script"); | |
script.id = "test-snippet"; | |
script.src = "https://test.api.com/test/snippet.js"; | |
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0] || document.getElementsByTagName('script')[0].parentNode).insertBefore(script, null); | |
console.log('the script is on the page but did not execute'); | |
console.log(typeof createdObj, 'does it exist?'); // -> undefined | |
// Standard Check | |
script.onreadystatechange = function (){ | |
// call setup when the script has beeen executed | |
if (this.readyState == 'complete'){ | |
setup(); | |
} | |
} | |
// IE Check | |
script.onload = setup; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment