Xiphias
Xiphias

Reputation: 4716

When should I call anonymous functions via jQuery and when via normal JavaScript?

I wondered what the difference of using jQuery or not using it might be considering the following task. I have not found any answer yet.

jQuery:

jQuery(function() { alert("Hello World!"); })
$(function() { alert("Hello World!"); })

Pure JavaScript:

(function() { alert("Hello World!"); })()

What is the difference? When should I use which approach? Thank you!

Upvotes: 0

Views: 76

Answers (4)

Adrian Roworth
Adrian Roworth

Reputation: 823

The main difference is that the jQuery functions are executed after the DOM is loaded. And the pure JavaScript lambda function is executed immediately (within its context).

The second jQuery function is shorthand for the first.

You could still put the JavaScript lambda function inside the jQuery wrapper. This would mean that the lambda function would execute right after the DOM has loaded (thanks to jQuery taking care of that).

Upvotes: 0

willy
willy

Reputation: 1490

The jQuery version binds to be executed once the DOM loads. The kind in just a closure executes as soon as it's defined. So if you want it to execute immediately, use the second version, if it should wait until everything's loaded, use the first.

At least, that's what I've got off the top of my head.

Upvotes: 0

what is sleep
what is sleep

Reputation: 905

$(function(){
  alert("hello world");
});

is short hand for:

$(document).ready(function(){
    alert("hello world");
});

so it will be executed after DOM loads.

while you pure js will be executed before DOM loads.

Upvotes: 0

Evan Davis
Evan Davis

Reputation: 36592

In general, $(function() { alert("Hello World!"); }) waits for $(document).ready() and the other function (an IIFE) fires immediately.

BUT the jQuery wrapped function is a very-specific use case (waiting for the DOM, using jQuery); your two examples are otherwise unrelated. Don't confuse them as 2 versions of the same thing.

Upvotes: 4

Related Questions