Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Lukas238/6ac50388aa0480959191 to your computer and use it in GitHub Desktop.
Save Lukas238/6ac50388aa0480959191 to your computer and use it in GitHub Desktop.
Pure JavaScript dynamic scripts loader + callback function

This pure javascript function allows to dynamically include a script and then execute any function by using a callback.

  
/**********************************
*	FUNCTIONS
***********************************/

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);
}

Usage

Callback function
function myfunction(){
	alert("Loaded");
}

loadScript("js/myscript.js", myfunction);
Custom function
loadScript("js/myscript.js", function(){
    alert("Loaded");
  }
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment