Skip to content

Instantly share code, notes, and snippets.

@fengyie007
Created November 21, 2013 04:47
Show Gist options
  • Save fengyie007/7576226 to your computer and use it in GitHub Desktop.
Save fengyie007/7576226 to your computer and use it in GitHub Desktop.
Lazy load scripts
// JavaScript
function loadScript(src, callback) {
var head = document.getElementsByTagName('head')[0],
script = document.createElement('script');
done = false;
script.setAttribute('src', src);
script.setAttribute('type', 'text/javascript');
script.setAttribute('charset', 'utf-8');
script.onload = script.onreadstatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
script.onload = script.onreadystatechange = null;
if (callback) {
callback();
}
}
}
head.insertBefore(script, head.firstChild);
}
// load the my-script-file.js and display an alert dialog once the script has been loaded
loadScript('my-script-file.js', function() { alert('my-script-file.js loaded.'); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment