Armin Ronacher

jQuery in Middlewares

written by Armin Ronacher, on Saturday, September 26, 2009 18:33.

Recently projects started using jQuery for middlewares that rewrite the request (like debug toolbars and similar stuff). This however breaks if another jQuery library is used on the page or if another library is in use because suddenly the $ or jQuery objects work differently.

However, because jQuery is awesome someone thought about that and added the deep-no-conflict mode. Let me show you a small example about how to use no compatible:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">
  (function($) {
    $(function() {
      $('body').html('jQuery is awesome');
    });
  })(jQuery.noConflict(true));
</script>

If you do this in a middleware inside the anonymous function you have access to your jQuery version you just included as $, but outside of it no trace of jQuery is left. Websites will continue to work in exactly the same way as before. Another word of warning: make sure to give your dom elements a really random class prefix in order to avoid clashes on the DOM level and in the CSS definitions. Also: append to things, not prepend. The latter could break first-child selectors people might use.

Comments

  1. Um, not quite true that "outside of it no trace of jQuery is left". The name "jQuery" is still there, as defined by the included file jquery-1.3.2.min.js. In theory that could still cause a conflict with another version of jQuery included elsewhere.

    —  Carl Meyer on Tuesday, September 29, 2009 17:38 #

  2. I second that - no conflict mode does not change meaning of $, but does define (or redefine) meaning of jQuery.

    However, if you can guarantee that your version of jQuery will be included before others - it will be pretty much safe.

    —  Serge Koval on Wednesday, October 7, 2009 7:16 #

  3. I love jQuery due to its simplicity to make animations such as fadeins/outs and the no conflict mode is just a bonus.

    —  Peter on Tuesday, February 16, 2010 15:09 #

Leave a Reply