Last active
October 5, 2015 19:37
-
-
Save travist/2863998 to your computer and use it in GitHub Desktop.
Dynamically add javascript to your page
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
// Conditionally loads scripts. | |
var loadScripts = function(params) { | |
// Iterate over each source. | |
var eachSource = function(callback) { | |
if (typeof params.scripts == 'string') { | |
callback(params.scripts); | |
} | |
else { | |
for (var i=0; i < params.scripts.length; i++) { | |
callback(params.scripts[i]); | |
} | |
} | |
}; | |
// Perform a test immediately. | |
if (!params.test()) { | |
// Add the sources to the code. | |
var tag = null; | |
var firstScriptTag = document.getElementsByTagName('script')[0]; | |
eachSource(function(source) { | |
tag = document.createElement('script'); | |
tag.src = source; | |
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); | |
}); | |
// Check every 200ms. | |
setTimeout(function tryAgain() { | |
if (params.test()) { | |
params.done(); | |
} | |
else { | |
setTimeout(tryAgain, 200); | |
} | |
}, 200); | |
} | |
else { | |
// Say we are done. | |
params.done(); | |
} | |
}; | |
// This example will load jQuery dynamically, but this could be any script... | |
loadScripts({ | |
test: function() { return typeof jQuery !== 'undefined'; }, | |
scripts: 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', | |
done: function() { | |
// Your code goes here... | |
console.log('jQuery Ready!'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment