Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active March 25, 2021 09:07
Show Gist options
  • Save LeanSeverino1022/331165154a967e83c9ff76bb6f1232f1 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/331165154a967e83c9ff76bb6f1232f1 to your computer and use it in GitHub Desktop.
Avoiding Conflicts with Other Libraries #jQuery #ajax

👍🏻 OK

Ways

Here's a recap of ways you can reference the jQuery function when the presence of another library creates a conflict over the use of the $ variable:

Create a New Alias

The jQuery.noConflict() method returns a reference to the jQuery function, so you can capture it in whatever variable you'd like:

<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
// Give $ back to prototype.js; create new alias to jQuery.
var $jq = jQuery.noConflict();
 
</script>

Use an Immediately Invoked Function Expression

⭐ My choice if it works for my use-case Continue to use the standard $ by wrapping your code in an immediately invoked function expression; this is also a standard pattern for jQuery plugin authoring, where the author cannot know whether another library will have taken over the $

<!-- Using the $ inside an immediately-invoked function expression. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
 
jQuery.noConflict();
 
(function( $ ) {
    // Your jQuery code here, using the $
})( jQuery );
 
</script>

Note: If you use this technique, you will not be able to use prototype.js methods inside the immediately invoked function. $ will be a reference to jQuery, not prototype.js.

Use the Argument That's Passed to the jQuery( document ).ready() Function

<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
 
jQuery(document).ready(function( $ ) {
    // Your jQuery code here, using $ to refer to jQuery.
});
 
</script>

Or using the more concise syntax for the DOM ready function:

<script src="jquery.js"></script>
<script src="prototype.js"></script>
<script>
 
jQuery(function($){
    // Your jQuery code here, using the $
});
 
</script>

for more, src is: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment