我有一个动态加载的jQuery,在<head>
元素将其插入脚本:jQuery的不可见后脚本元素动态地添加它
// pseudo code
headElelement.insertBefore(script, firstChild);
然而,这一呼吁后,我立即开始使用jQuery,但在那一刻它是不确定的。这怎么可能?
我有一个动态加载的jQuery,在<head>
元素将其插入脚本:jQuery的不可见后脚本元素动态地添加它
// pseudo code
headElelement.insertBefore(script, firstChild);
然而,这一呼吁后,我立即开始使用jQuery,但在那一刻它是不确定的。这怎么可能?
如果你想发布您的相关代码,它会更容易;-)但不管怎么说,这是做的一种可能的方式:
<html>
<head>
<script type="text/javascript" src="path_to_js/jquery.js"></script>
<script type="text/javascript" src="path_to_js/your_js_code.js"></script>
...
</head>...
,并在文件中your_js_code.js你必须:
... /* All your modules and functions here */
/* DOM loading ready */
$(document).ready(function() {
call_your_methods_here();
});
顺便说一句,它通常是更好地在HTML中<body>
,你的HTML开始显示第一和用户这样的最后加载您的JS文件“看到”你的网页速度更快,而JS代码仍在加载。
这是因为jQuery尚未完全加载。只有通过将事件处理程序附加到动态创建的脚本元素的onload
事件,才能加载jQuery,如下所示,您可能需要执行jQuery代码。
script.onload = function() {
// Put your jQuery code here.
console.log(jQuery);
};
支持旧的浏览器像IE8及以下跨浏览器的解决方案:
script.onload = script.onreadystatechange = function(event) {
event = event || window.event;
if (event.type === "load" || (/loaded|complete/.test(script.readyState))) {
script.onload = script.onreadystatechange = null;
// Put your jQuery code here.
console.log(jQuery);
}
};
如果代码你运行你的内心后插入后jQuery的一个'$(函数(){});'块? – atmd 2015-03-02 08:46:51
我只是运行这种代码while(typeof jQuery ==='undefined'){ }它永远运行 – Zed 2015-03-02 08:50:01
请发布相关的代码,否则它只是猜测:你是什么意思的伪代码,你真的在HTML本身加载jquery,如'
...'?你在哪里尝试使用它,你说“在那个电话后立即”,所以在头上? – Ariel 2015-03-02 08:55:09