Question

I have a simple function that I'd like to run on $.ready. The same function should run both on the frontend as well as on the admin pages.

Problem happens on the admin pages because there the jQuery variable is not defined. Instead they define django.jQuery.

How can I make my code fit both cases without polluting global namespace with an additional jQuery name?

This is what I have so far, it works, but leaves the additional jQuery name in global scope:

if(typeof jQuery === 'undefined' && typeof django !== 'undefined') {
   jQuery = django.jQuery;
}
jQuery(function($){...});
Was it helpful?

Solution

Not sure what the big deal with having jQuery in the global namespace. BUT you can do something like this:

(function (jQuery) { 
    jQuery(function($){...});
})(window.jQuery || django.jQuery));

or more confusing

(window.jQuery || django.jQuery)(jQuery(function($){...});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top