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($){...});
有帮助吗?

解决方案

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($){...});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top