[英]Run jQuery code once jQuery loaded
I have jQuery loaded before the closing tag on my page. 我在页面上的结束标记之前加载了jQuery。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
The majority of my js is loaded below this in 我的大部分js都在以下位置加载
<script src="js/script.js" type="text/javascript"></script>
Which works well. 哪个很好。 There is some ad code that I need to run in the head tag.
我需要在head标签中投放一些广告代码。 This works fine usually however I want to add a responsive exception.
通常,这可以正常工作,但是我想添加一个响应异常。 eg
例如
var mob = 0;
if(jQuery(window).width() < 727) {
mob = 1;
}
if(mob) {console.log('run special mob related code');}
else {console.log('run special desktop related code');}
Because my code is in the I get the error ReferenceError: jQuery is not defined. 因为我的代码在中,所以出现错误ReferenceError:jQuery未定义。 Is there a way around this?
有没有解决的办法? The ad code doesn't run unless it is in the head, but I can't really move the jquery into the head as I have this on multiple sites and may affect how other plugins run?
广告代码除非在头部,否则不会运行,但是我无法真正将jquery移入头部,因为我在多个站点上都有此代码,并且可能会影响其他插件的运行方式吗?
Why not just use something like this: 为什么不使用这样的东西:
if (document.documentElement.clientWidth < 727) {
mob = 1;
}
Early in your code, you could define a jQuery
property on the window
object, which will run your code that requires jQuery when it is reassigned by the actual jQuery object. 在代码的早期,您可以在
window
对象上定义一个jQuery
属性,当实际的jQuery对象将其重新分配时,它将运行需要jQuery的代码。
(function(){
var _jQuery;
Object.defineProperty(window, 'jQuery', {
get: function() { return _jQuery; },
set: function($) {
_jQuery = $;
// put code or call to function that uses jQuery here
}
});
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.