I have jQuery loaded before the closing tag on my page.
<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
<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. 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. 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?
2 Answers 2
Why not just use something like this:
if (document.documentElement.clientWidth < 727) {
mob = 1;
}
4 Comments
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.
(function(){
var _jQuery;
Object.defineProperty(window, 'jQuery', {
get: function() { return _jQuery; },
set: function($) {
_jQuery = $;
// put code or call to function that uses jQuery here
}
});
})();
jQueryvar or$unless you load jQuery library.. If you can't load it.. then don't use the jQuery var there..DOM ready handler