Difference between window.onload and $(document).ready()
Overview
Many web developers find it difficult to make their functions work when they launch a website. This is because most developers find it challenging to use the methods that make scripts work efficiently when a website loads.
Two popular methods are used to make functions work when a page loads:
- JavaScript’s
window.onloadevent - jQuery’s
$(document).ready()method
In this shot, we’ll explain how these functions are used and outline their differences.
Let’s get started!
The window.onload function
The onload method in JavaScript is associated with executing a JavaScript function once a page has loaded completely. This onload method is often used in the body, and a function is passed to it. This function is executed immediately after an object is loaded.
Note: When we say completely loaded, we mean when the page completely loads all of its content including media, script files, and even CSS files.
Proper versions of web pages are loaded using the onload method to get the visitor’s browser type and the browser version.
Syntax
The onload method can be implemented using various syntax. These include:
- HTML:
<element onload= "functionName"> - JavaScript:
object.onload = function(){myScript}; - The
addEventListener()method:object.addEventListener("load", myScript);.
Code example
One of the methods will be used below to demonstrate the work of the onload method:
Explanation
HTML section
- Line 7: We include an image with an id
imgin the page. - Line 9: We include an empty
ptag in the page. It has an idtextHolder.
JavaScript section
- Line 1: We use the
document.getElementByIdto call the image we interacted with. Then we invoke theonloadmethod using the pure JavaScript syntax. We include a function that is created in line 2 later. - Line 2: We. create a
onLoadFunctionfunction. This functions gets the emptyptag and include a text using the.innerHTMLmethod. The text shows once the page loads completely.
Note: Test the code by specifying a wrong
srcin theimg, notice that the text will not be displayed.
The $(document).ready() method
The$(document).ready() is a jQuery method that executes a block of code when the
The code block is put into the parenthesis and will be executed once the document is ready, neglecting the loading of images and other contents on the website.
Syntax
The syntax to invoke this event is:
$(document).ready(function)
Code example
We’ll use the same code example as above and explain the JavaScript section here:
Explanation
JavaScript Section
- Line 1: We call
$(document).ready(), and a function, which adds a text to the emptyptag after the image loads, is pushed into the parenthesis.
Conclusion
The major difference between the JavaScript’s onload and jQuery’s $(document).ready(function) method is that:
- The
onloadexecutes a block of code after the page is completely loaded while$(document).ready(function)executes a block of code once the DOM is ready.