NetOperator Wibby
NetOperator Wibby

Reputation: 1414

Is window.addEventListener("load", init); faster than $(function () { init(); });?

Like the title says.

I'm the front-end guy at my company and one of the back-end guys uses JavaScript while I use jQuery. I know there are strong opinions on either side of the fence and I'm not trying to start a battle here, I am just curious.

To me, it doesn't seem like it makes much of a difference, except that the JavaScript function starts at window load, whereas the jQuery function starts at document load.

Upvotes: 2

Views: 2448

Answers (2)

ajm
ajm

Reputation: 20105

Assuming you're talking about pure "when code runs" and ignoring outside variables (i.e. the overhead of including jQuery on a page), the jQuery method would be faster because it fires on the domcontentloaded event, which should occur sooner than window's load event.

Why is it faster? It fires when the DOM is available and before things like images have loaded. In an image-heavy site, that could be quite a difference in timing. window's load event fires after those resources load, which is likely going to occur later (sometimes much later) in your Document's lifecycle.

Upvotes: 1

Quentin
Quentin

Reputation: 944147

It depends on what you are measuring.

In terms of execution time, it will take longer to load all of jQuery and to run the code through the jQuery function then it will to call a single native method. (How much difference that makes depends on if you are going to be loading jQuery or not anyway).

In terms of when the init function will execute, load will generally fire a significant time after DOMReady since load waits for images, stylesheets, etc to finish loading.

You generally shouldn't be doing performance comparison when changing two variables anyway. jQuery Vs Native is a separate issue to DOMReady Vs Load.

You should also be cautious of premature optimisation

Upvotes: 5

Related Questions