I am trying to use jquery no conflict, but without success. I have deliberately included jquery twice in the page for testing purposes to get an error! I know jquery should only be included once, but the point is to try to make it bulletproof against poorly coded themes out there.
Here is the test case:
https://jsfiddle.net/v2jupagc/
If I include second jquery link after my JavaScript code block I get an error. How can I make no conflict work with my code?
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
(function($) {
$.fn.test = function(){console.log('1')}
})(jQuery);
</script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
if (!/loaded|interactive|complete/.test(document.readyState)) document.addEventListener("DOMContentLoaded",onLoad); else onLoad();
function onLoad() {
var nc = jQuery;
nc.noConflict();
nc("#wrapper").test();
}
</script>
Your current logic doesn't work because you overwrite the $
(which you added the $.test()
logic to) with the next reference to jQuery 3.3.1.
You need to call $.noConflict()
on the first version of jQuery that you load so that you retain a reference to it. Something like this, although note that nc
is now a reference to jQuery 1.12.4:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script type="text/javascript"> var nc = $.noConflict(); (function($) { $.fn.test = function() { console.log('1') } })(nc); </script> <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script type="text/javascript"> if (!/loaded|interactive|complete/.test(document.readyState)) document.addEventListener("DOMContentLoaded", onLoad); else onLoad(); function onLoad() { nc("#wrapper").test(); } // just to illustrate the point console.log('nc =', nc.fn.jquery); console.log('jQuery =', jQuery.fn.jquery); </script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.