Skip to content

Instantly share code, notes, and snippets.

@kaixiang-li
Created April 4, 2012 08:56
Show Gist options
  • Save kaixiang-li/2299786 to your computer and use it in GitHub Desktop.
Save kaixiang-li/2299786 to your computer and use it in GitHub Desktop.
script loader,load all the scripts from the script array
var a = "I'm a";
var b = "I'm b";
var c = "I'm c";
(function(window){
var group = [],queue = {},
head = document.head || document.getElementsByTagName("head")[0];
function require(scripts,callback,context){
group = group.concat(scripts);
context = context || this;
for( var i = 0 ; i < group.length ; i++){
var script = document.createElement("script");
script.type = "text/javascript";
if(queue[group[i]]){
//alert( group[i] + " has loaded");
continue;
}
if(script.readyState){ //for IE
script.onreadystatechange = function(){
var readyState = this.readyState;
if(readyState == "loaded" || readyState == "complete"){
this.onreadystatechange = null;
callback.call(context);
}
};
}
else{
script.onload = function(){
callback.call(context);
}
}
queue[group[i]] = true;
script.src = group[i] + ".js";
head.appendChild(script);
}
}
window.require = require;
})(this);
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
require(["a","b","c"],function(){
alert(a + b + c);
});
</script>
</body>
</html>
@houkanshan
Copy link

            if(queue[group[i]]){
                 alert( group[i] + " has loaded");
                 return;
            }

为啥这里是直接return而不是continue?

@kaixiang-li
Copy link
Author

嗯写错了 改掉:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment