Событие onload

HTML Атрибут событий onload

Выполненить JavaScript сразу после загрузки страницы:

Больше примеров «Попробуйте сами» ниже.

Определение и использование

Атрибут onload срабатывает, когда объект будет загружен.

Атрибут onload чаще всего используется в элементе для выполнения скрипта после того, как веб-страница полностью загрузила все содержимое (включая изображения, файлы скриптов, файлы CSS и т.д.). Однако его можно использовать и на других элементах (см. «Поддерживаемые теги HTML» ниже).

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

Атрибут onload также может использоваться для работы с файлами cookie (см. «Дополнительные примеры» ниже).

Читайте также:  line-height

Поддержка браузеров

Различий между HTML 4.01 и HTML5

Синтаксис

Значение атрибута

Технические подробности

Больше Примеров

Пример

С помощью события onload элемент . Предупреждение «Изображение загружено» сразу после загрузки изображения:

Пример

Использование события onload для работы с файлами cookie (с помощью javascript «advanced»):

function checkCookies() var text = «»;
if (navigator.cookieEnabled == true) text = «Cookies включены.»;
> else text = «Файлы cookie не включены.»;
>
document.getElementById(«demo»).innerHTML = text;
>

Связанные страницы

Источник

Событие 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

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

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

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

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

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

Видео

Документ

Звук

Изображения

Объекты

Скрипты

Списки

Ссылки

Таблицы

Текст

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

Формы

Фреймы

Источник

HTML onload Attribute

The onload attribute fires when an object has been loaded.

onload is most often used within the element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well (see «Supported HTML tags» below).

For input elements, the onload attribute is only supported when

The onload attribute can be used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.

Applies to

The onload attribute is part of the Event Attributes, and can be used on the following elements:

Examples

Body Example

Execute a JavaScript immediately after a page has been loaded:

Img Example

Using onload on an element. Alert «Image is loaded» immediately after an image has been loaded:

Input Example

Using onload on an element. Alert «Image is loaded» immediately after an image has been loaded:

Browser Support

The onload attribute has the following browser support for each element:

Element
body Yes Yes Yes Yes Yes
iframe Yes Yes Yes Yes Yes
img Yes Yes Yes Yes Yes
input type=»image» Yes Yes Yes Yes Yes
link Yes Yes Yes Yes Yes
script Yes Yes Yes Yes Yes
style Yes Yes Yes Yes Yes

Источник

HTML атрибут-событие onload

Событие onload возникает, когда объект загружен.

Чаще всего атрибут onload используют с тегом , чтобы выполнить скрипт, когда веб-страница полностью загрузила весь контент (включая изображения, файлы скриптов, файлы CSS и т.д.). Тем не менее, этот атрибут также может использоваться и с другими элементами (см. «Поддерживаемые HTML теги» ниже).

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

Также, атрибут onload может использоваться для работы с кукисами (см. Примеры).

Особенности
Поддерживаемые HTML теги: , , , , , , , ,

Синтаксис атрибута

Значения атрибута

Пример использования атрибута

Запускает скрипт сразу после загрузки страницы:

Использование атрибута onload с элементом . Сразу после загрузки изображения будет выведено сообщение «Изображение загружено»:

    function loadImage() 

Запускает скрипт для работы с кукисами:

    

Источник

How do I call a JavaScript function on page load?

This tutorial will teach us to call a JavaScript function on page load. In many cases, while programming with HTML and JavaScript, programmers need to call a function, while loading the web page or after the web page load finishes. For example, programmers need to show the welcome message to the user on page load, and the programmer needs to call a JavaScript function after the page load event.

There are various ways to call a function on page load or after page load in JavaScript, and we will look at them one by one in this tutorial.

  • Using the onload event in the tag
  • Using the window.onload Event
  • Using the DOMContentloaded Event

Using the onload event in the tag

The first approach for calling a function on the page load is the use an onload event inside the HTML tag. As you know, the HTML body contains the entire content of the web page, and when all HTML body loads on the web browser, it will call the function from the JavaScript.

Syntax

Follow the below syntax to use onload event in the tag.

Example

In the below example, we have created the JavaScript function named welcomeFunction(). We are calling that function from the tag using the onload event, and it shows the welcome message in the alert box to the users.

      

Methods to call a JavaScript function on page load.

Call the JavaScript function on page load by using onload event in the HTML body tag.

let message = document.getElementById("message"); function welcomeFunction()

When users run the example code, they will give the welcome message in the alert box. When function execution completes, users will get the above output message.

Using the window.onload Event in JavaScript

Here, we have a second approach for calling the function on page load in JavaScript. Every web page contains the window object by default, and the window object represents the global variables. We can access any global variable or function in JavaScript using the window object. In this approach, we will use the onload property of the window object.

By using the window.onload property, users can either call a named function or bind an anonymous function to the window.onload and all code inside the anonymous function will be executed after the page load.

Syntax

Users can follow the below syntax to use the window.onload to call a function on page load.

Function simpleFunction ( ) < // function body >Window.onload = simpleFunction( );

Example

In the below example, we are calling the named function on the page load using the window.onload property.

      

Methods to call a JavaScript function on page load.

Call the JavaScript function on page load by using window.onload event in the JavaScript.

window.onload = simpleFunction( 10, 20 ); // call function with parameters on page load function simpleFunction( num1, num2 )

Using the DOMContentLoaded Event

JavaScript has a cool feature of the event listener, and users can call a function or perform some operation when any event triggers. In this approach, we will use the “DOMContentloaded” event. We will call the desired function using the addEventListener() method in JavaScript. Also, we will apply the event listener to the whole document such that we can call a function on the page load.

Syntax

To call the DOMContentLoaded event, users can follow the below syntax.

document.addEventListener("DOMContentLoaded", function() < // function body >);

Example

The below example demonstrates the use of the DOMContentLoded event to trigger a function call on the page load.

      

Methods to call a JavaScript function on page load.

Call the JavaScript function on page load by using document.addEventListener( ) method.

let message = document.getElementById("message"); document.addEventListener( "DOMContentLoaded", functionCall()); function functionCall()

Users will also see the alert box with the message when the function will be executed.

Conclusion

Here, we have defined three approaches to trigger a function call on the page load. The first approach we can use inside the HTML code, the second one in the JavaScript code, and the third approach is the best approach to achieve our goal.

Furthermore, users can change the event in the third approach to trigger a function on a particular event. One more thing in the last approach is rather than triggering the event listener to the whole document, users can apply it to a specific HTML element also.

Источник

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