延迟加载JavaScript - 未捕获的ReferenceError:$未定义 [英] Defer loading of JavaScript - Uncaught ReferenceError: $ is not defined
问题描述
我使用谷歌代码推迟加载javascript(谷歌页面)
I use google code to defer loading javascript (google pages)
但我有一些内联javascripts,如:
But I have some inline javascripts such as:
<script type="text/javascript">
$(function () {
alert("please work");
});
</script>
这给了我:
未捕获的ReferenceError:$未定义
Uncaught ReferenceError: $ is not defined
我想我需要一些函数,它是在加载jQuery后触发的并初始化我的内联javascripts。但如果有另一种方式,我会很高兴。
I think I need some function, which was triggered after jQuery was loaded and init my inline javascripts. But if there is another way, I will be glad.
编辑:
你们中的一些人完全不在主题Mahesh Sapkal很接近。
Some of you are completely out of topic. Mahesh Sapkal was close.
使用此代码我没有错误,但仍然无法正常工作
With this code I have no error, but still don't work
<head>
<script type="text/javascript">
var MhInit = NULL;
// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
MhInit = element.src = "my_packed_scripts.js";
document.body.appendChild(element);
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
</head>
<body>
<script type="text/javascript">
MhInit.onload = function() {
console.debug("here");
};
</script>
</body>
推荐答案
你不能使用 jQuery
在加载之前。如果您移动页面底部的< script src =jquery.js/>
,您还必须移动所有使用 $(...)
低于它。
You cannot use jQuery
before it is loaded. If you move the <script src="jquery.js" />
at the bottom of your page you must also move all the lines that use $(...)
below it.
有一个棘手的解决方案可以解决这些问题:
There is a tricky solution that goes something along these lines:
1)在页面顶部定义几个变量:
1) Defining few variables at the top of your page:
var _jqq = [];
var $ = function(fn) {
_jqq.push(fn);
};
2)在页面中间你可以写:
2) In the middle of the page you can write:
$(function() {
alert("document ready callback #1");
});
$(function() {
alert("document ready callback #2");
});
3)在页面底部,包含jQuery:
3) At the bottom of your page, include jQuery:
<script src="//code.jquery.com/jquery.min.js"></script>
4)最后:
$(function() {
$.each(_jqq, function(i, fn) {
fn();
});
});
这篇关于延迟加载JavaScript - 未捕获的ReferenceError:$未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!