我有一个加载 jQuery 和其他一些 js 库的书签。
我如何能:
- 等到我正在使用的 javascript 库可用/加载。如果我在完成加载之前尝试使用脚本,例如在加载之前使用带有 jQuery 的 $ 函数,则会引发未定义的异常。
- 确保我加载的小书签不会被缓存(不使用服务器标头,或者显然,这是一个 javascript 文件:元标记)
有人知道动态添加的 javascript 的 onload 是否在 IE 中有效吗?(与这篇文章相矛盾)
对这些问题最简单、最干净的解决方案是什么?
我有一个加载 jQuery 和其他一些 js 库的书签。
我如何能:
有人知道动态添加的 javascript 的 onload 是否在 IE 中有效吗?(与这篇文章相矛盾)
对这些问题最简单、最干净的解决方案是什么?
这取决于您实际加载 jQuery 的方式。如果要将脚本元素附加到页面,则可以使用 jQuery 用于动态加载脚本的相同技术。
编辑:我做了功课,实际上从 jQuery 代码中提取了一个 loadScript 函数,以便在您的书签中使用。它实际上可能对许多人(包括我)有用。
function loadScript(url, callback)
{
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers for all browsers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
// Usage:
// This code loads jQuery and executes some code when jQuery is loaded
loadScript("https://code.jquery.com/jquery-latest.js", function()
{
$('my_element').hide();
});
要回答您的第一个问题:Javascript 是按顺序解释的,因此在加载库之前,任何后续的小书签代码都不会执行(假设库被成功解释 - 没有语法错误)。
为了防止文件被缓存,您可以附加一个无意义的查询字符串...
url = 'jquery.js?x=' + new Date().getTime();
我注意到在 Chrome 中,当使用@Vincent Robert 的技术时,加载脚本的顺序是不确定的。在这种情况下,稍作修改会有所帮助:
(function() {
var callback = function() {
// Do you work
};
// check for our library existence
if (typeof (MyLib) == 'undefined') {
var sources = [
'http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js',
'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js',
'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js',
'http://myhost.com/javascripts/mylib.min.js'];
var loadNextScript = function() {
if (sources.length > 0) {
var script = document.createElement('script');
script.src = sources.shift();
document.body.appendChild(script);
var done = false;
script.onload = script.onreadystatechange = function() {
if (!done
&& (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
done = true;
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
loadNextScript();
}
}
} else {
callback();
}
}
loadNextScript();
} else {
callback();
}
})();
我对此有了更深入的了解,但并非完全如此。如果有一个离散的小书签示例来演示如何避免缓存,那就太好了。