Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery document.ready vs pageLoad

Tags:

I've picked up an existing project from another developer and ive noticed in the code that they are executing js code within three different event handlers...

function pageLoad() {
//execute code
}

$(document).ready(function() {
//execute code
});

$(function() {
//execute code
});

My question is - arent they all exactly the same? Or at least the last two? I understand that pageLoad is called by the .NET framework so it's not dependent on the jQuery library having loaded like the second two are - that's my understanding anyway - is that about correct?

like image 374
higgsy Avatar asked Oct 19 '11 15:10

higgsy


People also ask

What is difference between document ready and document load?

load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc. are loaded, but after the whole DOM itself is ready.

What is the difference between document ready () and window onload ()?

ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window. onload event occurs later, when everything including images on the page loaded. Also window. onload is a pure javascript event in the DOM, while the $(document).

What is document ready in jQuery?

$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.

Is DOMContentLoaded the same as document ready?

ready() method differs in an important and useful way: If the DOM becomes ready and the browser fires DOMContentLoaded before the code calls . ready( handler ) , the function handler will still be executed. In contrast, a DOMContentLoaded event listener added after the event fires is never executed.


1 Answers

$(document).ready()

  • Ideal for one time initialization.

  • Optimization black magic; may run slightly earlier than pageLoad().

  • Does not re-attach functionality to elements affected by partial postbacks.

pageLoad()

  • Unsuitable for one time initialization if used with UpdatePanels.

  • Slightly less optimized in some browsers, but consistent.

  • Perfect for re-attaching functionality to elements within UpdatePanels.

like image 156
Sunny Avatar answered Sep 18 '22 09:09

Sunny