Al-Mothafar
Al-Mothafar

Reputation: 8219

$(function(){});, (function($)(){}(JQuery); and $(document).ready(function(){}); any difference?

I have a very strange issue with JQuery, its about a starting of JQuery code when document is ready, as I know there is no difference to use one of methods $(function(){//CODE});, (function($)(){//CODE}(JQuery) or $(document).ready(function(){//CODE});.

Like what said on What is the difference between $(document).ready(function() and $(function() ?

So I like always to use $(function(){//CODE}); method, but when I using this method in some pages working well, but in another I got errors like If I use $.fn.extend or $.browser.msie , I'll get '$.fn is undefined' issue, tried to use (function($)(){//CODE}(JQuery) and that error disappeared, I just want to know why this happening and really if there is and difference between each method !

Upvotes: 1

Views: 108

Answers (2)

solendil
solendil

Reputation: 8468

Probably a javascript import in the offending page is redefining the $ variable. This variable doesn't reference jQuery anymore, hence the error. When using the (function($)(){//CODE}(JQuery) construct, you create a closure where the $ variable is once again bound to the jQuery object, and everything goes well inside this closure.

Another way to avoid problems is to always use jQuery instead of $. Example : jQuery(function(){//CODE});

Upvotes: 2

El Ronnoco
El Ronnoco

Reputation: 11922

It looks like when you're getting the error, you have set jQuery.noConflict (or someone has).

$ is just an alias for jQuery - other frameworks use this too though.

There should be no problem using $(function(){code}) ..or.. jQuery(function(){code})

Upvotes: 0

Related Questions