Dynamically load and execute JavaScript method
This is a simple solution to load a JavaScript dynamically and call a method when done. For more advance solution take a look at requirejs.
1. Check what protocol we are currently using to ensure we are using a secure connection if current page is using secure connection to load our new JavaScript file.
2. Create a new script element
3. Create a callback function with a simple counter that will ensure that we only execute the new method once
4. Attach the new created callback function to onreadystatechange to be used be Internet Explorer and onload for other browsers. In onreadystatechange we add additional checks of the state to ensure we are only calling the callback when the dynamically script is completely loaded.
5. The last thing that is need is to add the new created script element to the header of current page.
var src; if (document.location.protocol === ""https:"") { src = 'https://mysite.com/thescript.js';} else { src = 'https//mysite.com/thescript.js'; } var script = document.createElement('script'); script.src = src; script.type = 'text/javascript'; var head = document.getElemenscriptByTagName('head')[0]; var called= 0; var callback = function() { if( called== 0) { called++; MethodInTheScript(); } }; // Inter explorer script.onreadystatechange = function() { if (this.readyState == 'complete') { callback(); } } //Other browsers script.onload = callback; head.appendChild(script); |