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:
window.onload
event$(document).ready()
methodIn this shot, we’ll explain how these functions are used and outline their differences.
Let’s get started!
window.onload
functionThe 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.
The onload
method can be implemented using various syntax. These include:
<element onload= "functionName">
object.onload = function(){myScript};
addEventListener()
method: object.addEventListener("load", myScript);
.One of the methods will be used below to demonstrate the work of the onload
method:
img
in the page.p
tag in the page. It has an id textHolder
.document.getElementById
to call the image we interacted with. Then we invoke the onload
method using the pure JavaScript syntax. We include a function that is created in line 2 later.onLoadFunction
function. This functions gets the empty p
tag and include a text using the .innerHTML
method. The text shows once the page loads completely.Note: Test the code by specifying a wrong
src
in theimg
, notice that the text will not be displayed.
$(document).ready()
methodThe$(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.
The syntax to invoke this event is:
$(document).ready(function)
We’ll use the same code example as above and explain the JavaScript section here:
$(document).ready()
, and a function, which adds a text to the empty p
tag after the image loads, is pushed into the parenthesis.The major difference between the JavaScript’s onload
and jQuery’s $(document).ready(function)
method is that:
onload
executes a block of code after the page is completely loaded while $(document).ready(function)
executes a block of code once the DOM is ready.