Friday 22 August 2014

Multiple version of jquery in the same Page

jQuery in no-conflict mode. "No conflict" mode is the typical solution to get jQuery working on a page with other frameworks like prototype, and can be also be used here as it essentially namespaces each version of jQuery which you load.
<script src="jQuery1.3.js"></script>
<script>
    jq13 = jQuery.noConflict(true);
</script>

<!-- original author's jquery version -->
<script src="jQuery1.2.3.js"></script>
<script src="jQuery1.3.js"></script>
<script>
    jq13 = jQuery.noConflict(true);
</script>
<script src="jQuery1.3.1.js"></script>
<script>
    jq131 = jQuery.noConflict(true);
</script>

<!-- original author's jquery version -->
<script src="jQuery1.2.3.js"></script>
The variables jq13 and jq131 would each be used for the version-specific features you require.
It's important that the jQuery used by the original developer is loaded last - the original developer likely wrote their code under the assumption that $() would be using their jQuery version. If you load another version after theirs, the $ will be "grabbed" by the last version you load, which would mean the original developer's code running on the latest library version, rendering the noConflicts somewhat redundant!
Why do conflicts happen? Conflicts typically happen because many JavaScript Libraries/Frameworks use the same shortcut name which is the dollar symbol $. Then if they have the same named functions the browser gets confused!
How do we prevent conflicts? Well, to prevent conflicts i recommend aliasing the jQuery namespace (ie by using example 3 above). Then when you call $.noConflict() to avoid namespace difficulties (as the $ shortcut is no longer available) we are forcing it to wrtie jQuery each time it is required.
1
2
3
4
5
6
7
8
9
10
jQuery.noConflict(); // Reverts '$' variable back to other JS libraries
jQuery(document).ready( function(){
         //do jQuery stuff when DOM is ready with no conflicts
   }); 
 
//or the self executing function way
 jQuery.noConflict();
 (function($) {
    // code using $ as alias to jQuery
})(jQuery);

No comments:

Post a Comment