我试图将我的长JavaScript代码分割成不同的库。Javascript通过代码添加js库
我试图写一个包装脚本,将加载我所有的库:
//this file loads all the scripts to the page
$(document).ready(function(){
var fileName = getCurrentFileName();
loadScript("scripts/pico/popups.js");
loadScript("scripts/pico/effects.js");
loadScript("scripts/pico/pico.js");
loadScript("scripts/pico/facebook.js");
if (fileName != null)
loadScript("script/pico/" + fileName + ".js");
});
/**
* Load a script to the body element
* @param name the name of script file.js
*/
function loadScript(name){
// Adding the script tag to the body
var body = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = name;
// Fire the loading
body.appendChild(script);
}
/**
* Get the current HTML file name
* @returns {*} the name of the file or null
*/
function getCurrentFileName(){
try {
var fileName;
fileName = document.location.pathname.match(/[^\/]+$/)[0];
return fileName.split('.')[0];
}
catch (e){
return null;
}
}
,但我认为facebook.js装载pico.js之前完成加载 - 这些都是从微微功能。 js里面的facebook.js ..
我怎样才能确保图书馆将按照我输入的顺序加载?
您需要使用onreadystatechange处理程序来确保它们按所需顺序加载。 –
http://stackoverflow.com/a/21246366/1959948 – Dalorzo
http://code.google.com/p/minify/根据需要合并,缩小和缓存JavaScript和CSS文件以加快页面加载速度。 – MrUpsidown