Adjit
Adjit

Reputation: 10305

TypeError thrown, but function still runs, why?

My console throws an uncaught typeError because it doesn't know what jQuery is yet, but then proceeds to execute the load, and load in the content, and then I get the load complete message.

I have the following code:

jQuery(function($){
    $('#content-loader').load('someFile.html', function() {
        console.log('load complete');
    });
})();

Why is that happening, and how can I get rid of the error and load in the html file?

As of now, someFile.html only contains text, no scripts.

Error Screen Cap: enter image description here

Attempted Solution

(function($){
  ...code...
})(jQuery);

Gets rid of the error, but does not load the html file

Upvotes: 0

Views: 131

Answers (1)

SparK
SparK

Reputation: 5211

You are basically calling jQuery(func)();. Passing a function to jquery might return a jquery object but not a function you can call with those last (). Your error message exactly: jQuery(..) is not a function because it's the return of a jQuery call, a jQuery object, not a function.

Try to use:

(function($){
  ...code...
})(jQuery);

Which is: Call this anonymous function that has parameter $ passing jQuery to it. That is a pattern a lot of people use.

Another quick (and weird) solution would be to remove your last () and the $ parameter from your wrapper.

Upvotes: 2

Related Questions