我发现了一个小的 javascript 片段,用于仅在之前未包含的情况下包含 javascript。
这是使用我自己的脚本,但使用两个第三方库时它不起作用,我真的不知道为什么。
var included_files = new Array();
function include_once(script_filename) {
if (!in_array(script_filename, included_files)) {
included_files[included_files.length] = script_filename;
include_dom(script_filename);
}
}
function in_array(needle, haystack) {
for (var i = 0; i < haystack.length; i++) {
if (haystack[i] == needle) {
return true;
}
}
return false;
}
function include_dom(script_filename) {
var html_doc = document.getElementsByTagName('head').item(0);
var js = document.createElement('script');
js.setAttribute('language', 'javascript');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', script_filename);
html_doc.appendChild(js);
return false;
}
function loaded() {
include_once("shared/scripts/jquery.min.js");
include_once("shared/scripts/iscroll.js");
$(document).ready(function () {
alert("hello");
});
}
错误:$ 未定义。 如果我以常规方式导入 jQuery,它会显示“iScroll”未定义(因为我稍后会使用它)。
有什么想法吗?
最佳答案
include_dom
是异步的。它并行加载脚本,您无法真正确定何时加载脚本。您尝试在开始下载后立即使用 jQuery,但这不起作用。
您需要使用允许您为加载的脚本指定回调的脚本。我会推荐 require.js
关于javascript - 包括 javascripts 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12969622/