Last active
June 15, 2016 07:34
-
-
Save codernik/c86d4331c8804be7eb79bae288a6e136 to your computer and use it in GitHub Desktop.
Javascript function for loading resources dynamically with onload 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
/** | |
* Accept three parameters | |
* @param {string} type : either js or css | |
* @param {string} url : url of the resource to be loaded | |
* @param {function} : function to be called back after resource loaded (Optional) | |
*/ | |
function loadResource(type, url, callbackFunction) { | |
var tag, mimeType; | |
if (type == 'js') { | |
tag = 'script'; | |
mimeType = 'text/javascript'; | |
} else { | |
tag = 'link'; | |
mimeType = 'text/css'; | |
} | |
var head = document.getElementsByTagName('head')[0]; | |
var resource = document.createElement(tag); | |
resource.type = mimeType; | |
resource.onreadystatechange = function() { | |
if (this.readyState == 'complete') | |
callbackFunction(); | |
} | |
if(typeof callbackFunction !== 'undefined') | |
resource.onload = callbackFunction; | |
if (type == 'js') { | |
resource.src = url; | |
} else { | |
resource.href = url; | |
resource.rel = 'stylesheet' | |
} | |
head.appendChild(resource); | |
} | |
/** | |
* Example : loading bootstrap css file | |
* with callback function alerting load complete | |
*/ | |
loadResource( 'css', 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css', | |
function(){ | |
alert('Resource load complete.'); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment