Dynamically Load External JS File

  • Javascript - June 3, 2016

There are times when you may need to load an external Javascript library dynamicaly and not via a static <script> tag such as:

<script type="text/javascript" src="http://yoursite.com/external.js"></script>

The following js code snippet can be added to an existing function to be loaded when needed...


 

// Dynamically Load Flashtalking API
function loadScript(url, callback){
	var script = document.createElement("script")
	script.type = "text/javascript";

	if (script.readyState){ //IE
		script.onreadystatechange = function(){
			if (script.readyState == "loaded" || script.readyState == "complete"){
				script.onreadystatechange = null;
				callback();
			}
		};
	} else { //Others
		script.onload = function(){
			callback();
		};
	}
	script.src = url;
	document.getElementsByTagName("head")[0].appendChild(script);
}
		
loadScript("http://yoursite.com/external.js", function(){ });

xx

Comments