嘿所有我尝试的东西(因为我很无聊)可以使用每个函数作为js文件,但如果只需要文件将bi bipended。所以我写了这样的东西。这个网站的一些部分。
library.js:
var jsfiles = new Array(
"jsLibrary/try.js",
"jsLibrary/try2.js"
);
var loadedJsFiles = [];
function loadFile(filepath,callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = filepath;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
function loadalljs(callback,jsnum){
if(!jsnum){jsnum = 0;}
if(jsnum<jsfiles.length){
if(!isArrayNode(jsfiles[jsnum],loadedJsFiles)){
loadedJsFiles.push(jsfiles[jsnum]);
loadFile(jsfiles[jsnum],function(){
loadalljs(callback,jsnum+1);
});
}else{
loadalljs(callback,jsnum+1);
}
}else if(jsnum==jsfiles.length){
callback();
}
}
function isArrayNode(str, arr) {
for (var i = 0; i < arr.length; i++) {
if (str == arr[i]) {
return true;
}
}
return false;
}
function lb(){
this.scripts = function(callback,includePageJs){
loadalljs(function(){
if(includePageJs){
loadFile(includePageJs,function(){
callback();
})
}else{
callback();
}
});
};
this.a = 5;
}
var library = new lb;
try.js:
function tryfunction(){
alert("try");
}
try2.js:
function try2(){
alert("try2");
}
mypage.js:
function mypagefunction(){
alert("mypagejs");
}
我正在使用它:
<script type="text/javascript" src="jsLibrary/library.js"></script>
<script>
library.scripts(function(){
tryfunction();
try2();
mypagefunction();
},"jsLibrary/mypagejs.js");
library.scripts(function(){
alert(library.a)
});
</script>
有没有办法以简单的方式做到这一点?感谢任何想法或帮助。 (请不要在jquery中)
答案 0 :(得分:4)
<script>
requirejs.config({
paths: {
'try1': '../path_to_your_try.js',
'try2': '../path_to_your_try2.js',
'mypage': '../path_to_your_mypage.js',
}
});
require([
'try1', 'try2', 'mypage'
], function(Try1, Try2, MyPage){
// Try1 refer to try1 file
// Try2 refer to try2 file
// MyPage refer to mypage file
});
</script>