Событие onload

JavaScript onload

Summary: in this tutorial, you will learn how to handle the load event that fires on the document, image, and script elements in JavaScript.

The window’s load event

For the window object, the load event is fired when the whole webpage (HTML) has loaded fully, including all dependent resources, including JavaScript files, CSS files, and images.

To handle the load event, you register an event listener using the addEventListener() method:

window.addEventListener('load', (event) => < console.log('The page has fully loaded'); >);Code language: JavaScript (javascript)

Or use the onload property of the window object:

window.onload = (event) => < console.log('The page has fully loaded'); >;Code language: JavaScript (javascript)

If you maintain a legacy system, you may find that the load event handler is registered in of the body element of the HTML document, like this:

html> html> head> title>JS load Event Demo title> head> body onload="console.log('Loaded!')"> body> html>Code language: HTML, XML (xml)

It’s a good practice to use the addEventListener() method to assign the onload event handler whenever possible.

The image’s load event

The load event also fires on images. To handle the load event on images, you use the addEventListener() method of the image elements.

The following example uses the load event handler to determine if an image, which exists in the DOM tree, has been completely loaded:

html> html> head> title>Image load Event Demo title> head> body> img id="logo"> script> let logo = document.querySelector('#logo'); logo.addEventListener('load', (event) => < console.log('Logo has been loaded!'); >); logo.src = "logo.png"; script> body> html> Code language: HTML, XML (xml)

You can assign an onload event handler directly using the onload attribute of the element, like this:

img id="logo" src="logo.png" onload="console.log('Logo loaded!')"> Code language: HTML, XML (xml)

If you create an image element dynamically, you can assign an onload event handler before setting the src property as follows:

window.addEventListener('load' () => < let logo = document.createElement('img'); // assign and onload event handler logo.addEventListener('load', (event) => < console.log('The logo has been loaded'); >); // add logo to the document document.body.appendChild(logo); logo.src = 'logo.png'; >); Code language: JavaScript (javascript)
  • First, create an image element after the document has been fully loaded by placing the code inside the event handler of the window’s load event.
  • Second, assign the onload event handler to the image.
  • Third, add the image to the document.
  • Finally, assign an image URL to the src attribute. The image will be downloaded to the element as soon as the src property is set.
Читайте также:  Файл в формате css

The script’s load event

The element also supports the load event slightly different from the standard ways. The script’s load event allows you to check if a JavaScript file has been completely loaded.

Unlike images, the web browser starts downloading JavaScript files only after the src property has been assigned and the element has been added to the document.

The following code loads the app.js file after the page has been completely loaded. It assigns an onload event handler to check if the app.js has been fully loaded.

window.addEventListener('load', checkJSLoaded) function checkJSLoaded( ) < // create the script element let script = document.createElement('script'); // assign an onload event handler script.addEventListener('load', (event) => < console.log('app.js file has been loaded'); >); // load the script file script.src = 'app.js'; document.body.appendChild(script); >Code language: JavaScript (javascript)

Summary

  • The load event occurs when the document has been completely loaded, including dependent resources like JavaScript files, CSS files, and images.
  • The and elements also support the load event.
  • Use the addEventListener() method to register an onload event handler.

Источник

What is the Window onload event in JavaScript?

With the new advancements in web development, JavaScript is even evolving in different frameworks, which makes life easy for developers. Talking about its use, as of now many famous websites are built on JavaScript which depicts how reliable this language is.

JavaScript has a window onload event to launch certain functions whenever a web page is loaded. The onload event is also used for verification of type and version of visitor’s browser. Further cookies can also be checked through the onload attribute.

The attribute of onload triggers when the object is loaded in HTML. This is to launch the script whenever the associated element loads. In simpler words, we can say that the window onload event is triggered whenever a web page is launched successfully.

Onload event is used with to run a script once its substance (which includes CSS files, images, and scripts) of the page is triggered completely. However, you do not always need a tag. It can be used with other Html elements.

Читайте также:  Php использование метода в методе

The download.onload launches before the images and external contents, triggered just before the window.onload. Whereas, window.onload starts after the page is completely loaded including CSS, script files, images, and many more.

If you want to manipulate load event in JavaScript, then you need to register event listener through method of addEventListener() as shown in the example below:

window. addEventListener ( ‘load’ , ( event ) => {

You can also handle the load event through the property of the window object i.e. onload. The example below shows how to use onload property:

Window.onload Event in the head section of HTML

First of all, we are going to present a simple example of a window.onload event. In this example, we simply display an alert message whenever a page is loaded.

alert ( » Hello, you are learning onload event in JavaScript» ) ;

window. onload = js_onload_code ( ) ;

Onload Event in the body section of HTML

Content can be displayed in the body section of HTML. Whenever the webpage is loaded then the event which occurred at that time is named onload event. We can use the onload event in the body section so that we can execute the script.

If you want to use an onload event within the body section then run the following code.

alert ( » Hello, you are learning onload event in JavaScript» ) ;

Window Onload Event in the body section of HTML

The object of the onload window represents the window of the browser. Whenever all the operations are completely loaded then onload property processes the load event. The function which we want to execute is allocated to the handler function of the onload property. Whenever the webpage gets loaded then the function will be executed. We have provided you with an example below.

window. onload = function functionName ( ) {

< b >What is window onload event in JavaScript ?

< p >Script Executed. Now you can check your console to see the output.

window. onload = function your_function_name ( ) {

console. log ( ‘Hey, you are learning window onload event in JavaScript. Script will be loaded.’ ) ;

Output of Console

If you want to see the output of the console then you have to open devTool by pressing the shortcut keys i.e. CTRL+SHIFT+ I. After opening the Devtool, you will be able to see the console’s output screen as shown below.

Conclusion

We have learned about what window.onload() event is and also learned the syntax of onload event. We briefly discussed several methods of how to write onload events in JavaScript along with an example. To recap, window.onload() event triggers after the web page has been loaded. We also see that the onload event is useful to set the version of browsers and also used to observe the cookies of a web page.

Читайте также:  Time series analysis python github

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.

Источник

Событие onload

Событие onload используется как указатель, что веб-страница полностью загружена, включая содержание, изображения, стилевые файлы и внешние скрипты.

Синтаксис

Значения

Значение по умолчанию

Применяется к тегам

Пример

     @keyframes _transparent < from < opacity: 0; >to < opacity: 1;>> @-webkit-keyframes _transparent < from < opacity: 0; >to < opacity: 1;>> @-moz-keyframes _transparent < from < opacity: 0; >to < opacity: 1;>> #status function loadPage()  

В данном примере после загрузки страницы будет выведено сообщение «Страница загружена».

Не выкладывайте свой код напрямую в комментариях, он отображается некорректно. Воспользуйтесь сервисом cssdeck.com или jsfiddle.net, сохраните код и в комментариях дайте на него ссылку. Так и результат сразу увидят.

Типы тегов

HTML5

Блочные элементы

Строчные элементы

Универсальные элементы

Нестандартные теги

Осуждаемые теги

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

Форматирование

Формы

Фреймы

Источник

window.onload for executing as soon as page loads

Window Onload

Window.onload function we can use to perform some task as soon as the page finishes loading. This JavaScript function is used in different condition like displaying a print page or directing focus ( keeping the crusher blinking ) to user input field as soon as the page is loaded.

JavaScript Window onload to execute script as soon as page loads and difference between body onload

Using body tag

The other way to achieve the same result is by using onload inside body tag of the page. You can read this article on how to keep the onload event handler to set the focus on input tag once the page loads. �

Let us start some simple example of uses of window.onload function where we will display one Alert box once the page loads.
demo of window onload event →
Here is the script

     

Difference between window.onload function and body tag onload.

wondow.onload is executed when full page is loaded to the browser ( including all images, style , scripts ,CDN etc )
document.onload is executed when DOM is ready ( Not necessarily all connected script, images etc to be downloaded )

We can’t keep any code to access the property set or any other related objects of the elements present in body of the page by using window.onload function.

Say we want to select the text present inside a text box as soon as the page loads. This is not possible by using window.onload event but this is possible by using body onload command. The code below will generate error message.

      

plus2net.com

Источник

Оцените статью