【发布时间】:2014-02-13 03:37:20
【问题描述】:
我正在尝试将我的长 JavaScript 代码拆分到不同的库中。
我正在尝试编写一个包装脚本来加载我的所有库:
//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 完成加载之前加载的 - 这些是 facebook.js 中 pico.js 中的函数..
我如何确保这些库将按照我输入的顺序加载?
【问题讨论】:
-
您需要使用 onreadystatechange 处理程序来确保它们按要求的顺序加载。
-
code.google.com/p/minify 按需组合、缩小和缓存 JavaScript 和 CSS 文件以加快页面加载速度。
标签: javascript jquery