我有一个脚本,它通过将jQuery插入到<head>元素中来动态加载它:
// pseudo code
headElelement.insertBefore(script, firstChild);然而,在那次调用之后,我立即开始使用jQuery,但在那一刻它是未定义的。这怎么可能呢?
发布于 2015-03-02 17:19:34
这是因为jQuery还没有完全加载。您可能只需要在加载jQuery之后执行jQuery代码,方法是将事件处理程序附加到动态创建的脚本元素的onload事件上,如下所示。
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);
}
};发布于 2015-03-02 17:11:07
如果你愿意发布你的相关代码,这将会更容易;-)但不管怎样,这是一种可能的方法:
<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>末尾加载JS文件通常更好,这样您的HTML首先开始显示,用户可以更快地“看到”您的页面,而JS代码仍在加载。
https://stackoverflow.com/questions/28805588
复制相似问题