大家下午好!我在网上搜索了解决这个问题的方法,并尝试实现我所看到的解决方案,但我仍然偶尔会遇到问题......
该项目采用模块化设计,每个模块都有一个 .html、.js 和 .css 文件。加载模块时,会检查那些关联的文件,如果它们已经存在于 DOM 中(例如,该模块已经至少打开过一次),那么就没有问题。如果文件尚未加载(例如,模块尚未加载),那么有时我会遇到调用 javascript 函数但外部 .js 文件尚未加载的问题。以下是负责处理此问题的函数:
function loadFile(sType,sURI,sCallback) {
// sType the type of file to load: link, script
// sURI the URI of the file to load
// sCallback the code to execute after successfully loading the file
var ref = document.createElement(sType);
if (sType == 'script') {
ref.setAttribute("type","text/javascript");
ref.setAttribute("src",sURI);
} else if (sType == 'link') {
ref.setAttribute("rel","stylesheet");
ref.setAttribute("type","text/css");
ref.setAttribute("href",sURI);
}
ref.async = true;
ref.onreadystatechange = ref.onload = function() {
var state = ref.readyState;
if (! sCallback.done && (! state || /loaded|complete/.test(state))) {
sCallback.done = true;
if (typeof(sCallback) === 'function') {
callback();
} else {
eval(sCallback);
}
}
};
document.getElementsByTagName('head')[0].appendChild(ref);
}
还有其他几篇 SO 文章用于上述功能:
Dynamically load external javascript file, and wait for it to load - without using JQuery
Javascript check if function exists
所以上面的函数将被调用如下:
loadFile('link',"module.css?cache=0", $("#divModule").hide().load("module.php?action=init").fadeIn('slow'));
loadFile('script',"module.js?cache=0", "initModule('req')");
下载 .css 文件后,第一次调用将加载模块的 .html 文件内容(通过 module.php 调用)。第二次调用将在 .js 文件下载后调用模块 js 初始化函数。
.css 文件似乎没有任何问题,但有时模块无法正确加载,这意味着布局渲染正确,但没有填充任何值(这就是模块 js init 函数发生的情况) 。如果我检查 FF 中的“Web 控制台”,则不会引发任何错误。有什么想法吗?
谢谢, 戴夫
最佳答案
对我来说很难说不知道 module.php 代码中发生了什么,但在我看来,你的第一个代码至少是立即触发的,而不是作为回调。除非我遗漏了什么,否则回调应该是一个函数,而现在当您调用 loadfile
时,您实际上正在执行 jquery hide/load 内容。您可能想将其包装在一个函数中。
关于javascript - 文件加载不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24867990/