jQuery noConflict() problem

2019-05-11 06:57发布

问题:

So I'm developing on a platform that injects jQuery-1.2.6 every time when a page loads. I developed my page to use jQuery-1.4.2, so when my page loads there are 2 jQuery instances on my page.

To avoid any conflict, I've included the following line in my JS file that is outside my page:

var mc$ = jQuery.noConflict();
jQuery(function($)

Everything seems to be working if I use mc$ for where the $ was originally used.

I am getting an error in Firebug and IE that I don't know how to resolve.

Within a file that is injected on the platform when my page loads the developer has done:

 $(document).ready(function() {

and the error in Firebug states: '$ is not a function'.

This error only started to show up once I made the change of:

var mc$ = jQuery.noConflict();

I'm thinking that by creating the mc$ variable that something broke with the developer's $(document)... call. If so, I don't know how to resolve this and if not I would hope there is a solution that I can put into place to provide the functionality back to the developer's injected file.

Thanks!

回答1:

A call order in your <head> section must be next:

  1. jQuery library №1;
  2. noConflict for it;
  3. jQuery library №2.

.noConflict() can look like this:

<script type="text/javascript">var mc$ = jQuery.noConflict();</script>

And after use this syntax in the scripts:

mc$('#container').height();


回答2:

The root cause is loading two instances of jQuery into one page. By the sounds of it, the original instance (1.2.6) of jQuery is also being unbound from the global $ variable.

From looking at http://api.jquery.com/jQuery.noConflict/, you could try supplying an additional parameter to the jQuery.noConflict() call to denote unloading jQuery as well, as it seems your instance of 1.4.2 is being loaded before 1.2.6.

Beyond that, without testing that exact scenario I don't know what other help to offer :)



回答3:

You may find this answer helpful: jquery noConflict not working in IE8 only