Javascript on windows load

Пройдите тест, узнайте какой профессии подходите

Работать самостоятельно и не зависеть от других

Работать в команде и рассчитывать на помощь коллег

Организовывать и контролировать процесс работы

Быстрый ответ

Если вам необходимо выполнить код JavaScript сразу по факту готовности DOM, воспользуйтесь событием DOMContentLoaded:

А если требуется дождаться загрузки всех ресурсов, включая графику, используйте window.onload:

Выбирайте, что для вас первостепеннее: скорость (DOMContentLoaded) или минимальное количество ошибок (window.onload).

Кинга Идем в IT: пошаговый план для смены профессии

Варианты запуска функции по завершении загрузки страницы

Существуют разнообразные методы запуска функции после полной загрузки страницы, и каждый из них имеет свои особенности.

Классический метод: window.onload

Данный метод обеспечивает загрузку всего, что есть на странице, включая внешние ресурсы.

Для любителей театральных сравнений: document.onreadystatechange

Состояние загрузки страницы постепенно меняется. В итоге, когда наступает «большой финал» (т.е. состояние становится 'complete'), готовность страницы окончательна.

Для тех, кто ещё использует jQuery: событие load

Следует также рассмотреть этот вариант:

Распространённые ловушки и ошибки

Не столь безопасный выбор: DOMContentLoaded

DOMContentLoaded срабатывает быстро, но не дожидается полной загрузки всех ресурсов.

Избегайте: нестандартные методы

Те, кто пытается быть излишне оригинальным и использует события onload для тегов <img> и других, легко могут попасть в ловушку неподдерживаемых функций. Простыми словами, лучше избегать подобных приёмов.

Источник замешательства: события выгрузки

Не путайте объем работ с window.onunload и window.onbeforeunload. Эти события подходят для работы в других контекстах и не имеют никакого отношения к загрузке страницы.

Приёмы работы с событиями загрузки

Точец внимания: обработчик события load

Инструкция addEventListener позволяет перехватить момент полной загрузки сайта наиболее эффективно при помощи события load:

Визуализация

Изучение событий загрузки и сопутствующих аспектов

Готовность: DOMContentLoaded

Событие DOMContentLoaded идеально подходит, если вам нужен быстрый старт. Ведь оно срабатывает по факту готовности HTML.

Порядок событий

Событие DOMContentLoaded, которое предшествует window.onload, отрабатывает первым, позволяя сайту стать интерактивным как можно скорее.

Динамическая загрузка контента

Если информация на вашей странице обновляется динамически, DOMContentLoaded и window.onload могут не дать вам всю необходимую информацию. Иногда необходим гибкий подход: проверка наличия элементов или событий после выполнения кода.

Отслеживание будущих загрузок

Если сайт наполняется контентом в процессе его работы, например при прокрутке страницы, может потребоваться применение новых событий или MutationObserver для отслеживания изменений в DOM.

Полезные материалы

  1. Событие load в window – Web API | MDN — подробная наработка по событию window.onload.
  2. .ready() | Документация API jQuery — как используется метод .ready() в jQuery для выполнения кода после загрузки DOM.
  3. HTML DOM метод addEventListener() — управление событиями браузера на W3Schools.
  4. javascript – window.onload vs document.onload – Stack Overflow — Сравнение window.onload и document.onload на ресурсе Stack Overflow.
  5. Can I use…Таблицы поддержки для HTML5, CSS3 и др. — информация о совместимости браузеров с событием DOMContentLoaded.
  6. Страница: DOMContentLoaded, load, beforeunload, unload | JavaScript.info — различные события загрузки страницы и их обработка в JavaScript.
  7. Событие DOMContentLoaded в документе – Web API | MDN — справочная информация о событии DOMContentLoaded на MDN.

Last Updated :
24 Apr, 2025

When a webpage loads, it takes time. The browser reads the HTML, builds the Document Object Model (DOM), and starts rendering the page. If your JavaScript runs too early, it might try to change elements that aren’t ready yet, causing errors. Running JavaScript after the page loads makes sure all the elements are ready for your script to work with.

How to Execute JavaScript After Page Load

There are several common methods to run JavaScript after the page has finished loading. These methods vary in terms of how they detect when the page load is complete and how they execute the script. Below are the following methods by which we can execute JavaScript after page load.

1. Using the window.onload Event

The window. onload event runs JavaScript only after the entire page, including images and other resources, has fully loaded.

Syntax

window.onload = function() {
    // Your JavaScript code here
};

Now let us understand this with the help of an example:

HTML

<html>
<head>
</head>
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h1>
        Using the window.onload event
    </h1>
    <p id="message"></p>
    <button onclick="location.reload()">
        Refresh Page
    </button>
    <script>
        window.onload = function () {
            setTimeout(function () {
                document.getElementById('message').innerHTML =
                    'The page has finished loading! After 5 second';
            }, 5000); 
        };
    </script>
</body>
</html>

Output

In this example:

  • The page has two headings, a paragraph, and a refresh button.
  • The window.onload event triggers when the page is fully loaded.
  • After 5 seconds, the paragraph’s text changes to «The page has finished loading!».
  • The button reloads the page when clicked.
  • The code ensures the message updates after a delay once the page has loaded.

2. Using the DOMContentLoaded Event

The DOMContentLoaded event is a more efficient way to run JavaScript after the initial HTML document has been completely loaded and parsed.

Syntax

document.addEventListener('DOMContentLoaded', function() {
    // Your JavaScript code here
});

Now let’s understand this with the help of example:

HTML

<html>
<head>
    <title>
        Using the DOMContentLoaded event
    </title>
</head>
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h1>
        Using the DOMContentLoaded event
    </h1>
    <p id="message"></p>
    <button onclick="location.reload()">
        Refresh Page
    </button>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            setTimeout(function () {
                document.getElementById('message').innerHTML =
                    'The page has finished loading! After 5 second';
            }, 5000); 
        });
    </script>
</body>
</html>

Output

In this example:

  • The page contains two headings, a paragraph, and a refresh button.
  • The DOMContentLoaded event triggers when the HTML is fully loaded and parsed (without waiting for images and styles).
  • After 5 seconds, the paragraph’s text updates to «The page has finished loading!».
  • The button reloads the page when clicked.
  • The code ensures the message appears 5 seconds after the page content is ready.

3. Using the defer Attribute

The defer attribute ensures that JavaScript is executed only after the HTML document has been fully parsed, but before other resources like images and styles are loaded. This allows the script to run as soon as the DOM is ready, without blocking the page rendering.

Syntax

<script src="script.js" defer></script>

Now let’s understand this with the help of example:

HTML

<html lang>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Using the DOMContentLoaded event</title>
</head>
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h1>
        DOMContentLoaded Event with defer
    </h1>
    <p id="message"></p>
    <button onclick="location.reload()">Refresh Page</button>
    <script defer>
        document.addEventListener('DOMContentLoaded', function () {
            setTimeout(function () {
                document.getElementById('message').innerHTML =
                    'The page has finished loading! After 5 seconds';
            }, 5000);
        });
    </script>
</body>

</html>

Output

In this example:

  • The <script> uses the defer attribute to execute after HTML parsing.
  • It listens for the DOMContentLoaded event.
  • After 5 seconds, it updates the message in the paragraph.
  • A button reloads the page when clicked.

4. Using the async Attribute

The async attribute allows JavaScript to be executed as soon as it’s downloaded, without waiting for the page or other resources to load. This can result in the script executing before or after the DOM is ready, depending on the download speed of the script

Syntax

<script src="script.js" async></script>

Now let’s understand this with the help of example:

HTML

<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Using async in script</title>
</head>
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h1>
        Using async in the script
    </h1>
    <p id="message"></p>
    <button onclick="location.reload()">Refresh Page</button>
    <script async>
        // This script will execute as soon as it is available.
        setTimeout(function () {
            document.getElementById('message').innerHTML =
                'The script has executed asynchronously after loading.';
        }, 5000);
    </script>
</body>
</html>

Output

In this example:

  • The script uses the async attribute, so it runs as soon as it’s ready, without waiting for the entire page to load.
  • After 5 seconds, the script updates the message in the paragraph (<p>).
  • A button reloads the page when clicked.
  • The message displayed says, «The script has executed asynchronously after loading.»

Why Execute JavaScript After Page Load?

  • Ensure All Elements are Loaded: Running JavaScript after the page loads ensures all HTML elements are available to interact with (e.g., DOM elements).
  • Prevent Blocking Page Rendering: JavaScript executed before the page is fully loaded can block the rendering of content, slowing down the user experience.
  • Improve Performance: By executing JavaScript after the page is loaded, you avoid delaying the page’s display, improving perceived performance.
  • Avoid Errors: Accessing elements before they are available can lead to errors. Running scripts after the page load ensures all elements are accessible.
  • Load External Resources: If JavaScript depends on external files (like images or APIs), waiting until the page load ensures those resources are ready for use.

Best Practices

  • Use events like DOMContentLoaded or the defer attribute to manipulate DOM elements without blocking other resources from loading.
  • Ensure your JavaScript doesn’t block the page from rendering by using the defer attribute or loading scripts asynchronously.
  • Reduce the use of external scripts that slow down the page load. Use defer or async to prevent blocking if you must use them.
  • Stick to native methods like DOMContentLoaded or window.onload instead of relying on libraries like jQuery, unless needed.

Conclusion

The article explained different methods to run JavaScript after a page loads, including using window.onload for full page load, DOMContentLoaded for HTML-only readiness, defer to run scripts after HTML parsing, and async to execute scripts as soon as they are downloaded, each serving specific needs based on when and how the script should execute.

В JS, манипуляции с тегами рекомендуется выполнять после полной загрузки DOM-дерева. Для этого есть события DOMContentLoaded и onload, в jQuery функция ready, рассмотрим их применение.

1

jQuery document ready

Сработает как только браузер полностью загрузит HTML и построит DOM-дерево.

$(document).ready(function(){
	console.log('Готов!');
});

JS

Сокращенный аналог

$(function(){
	console.log('Готов!');
});

JS

2

DOMContentLoaded

Тоже самое что и document.ready.

document.addEventListener('DOMContentLoaded', function(){
	console.log('Готов!');
});

JS

3

window.onload

В отличии от DOMContentLoaded и ready, событие onload срабатывает после полной загрузки всех ресурсов (например, изображения).

window.onload = function(){
	console.log('Готов!');
};

JS

Вариант на jQuery

$(window).on('load', function(){
	console.log('Готов!');
});

JS

Также событие можно задать атрибутом onload у тега <body>.

<!DOCTYPE HTML>
<html>
<head>
	...
</head>
<body onload="console.log('Готов!');">
	...
</body>
</html>

HTML

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

  • Что такое window.onload

    Иногда, происходит такое, что вы, вроде бы и написали все правильно, но скрипт… просто не работает. И непонятно почему.

    Одна из причин — это загрузка скрипта раньше, чем самой страницы. Ваш скрипт — тупо не видит код ниже себя.

    Для этого существует window.onload

    window — объект.

    onload — это «событие». Иногда, на просторах интернета можно встретить разное название для этого события, но «onload» — это «Event», а в переводе — это событие.

    1). Используем window.onload на странице :

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

    <script>

    window.onload = function() {

    alert(‘Страница загружена’);

    };

    </script>

    2). Используем window.onload в отдельном файле :

    Если у вас подключенный скрипт, то теги <script> и </script> не нужны.

    window.onload = function() {

    здесь помещаем все, что угодно…

    };

    3). Используем onload и object в качестве объекта загрузки :

    object может быть например body или window, естественно к этому объекту, сперва нужно обратиться.

    object.onload

    object.onload=function(){/**код**/};

    4). onload в HTML

    В качестве атрибута onload, возможно использование в HTML :

    <element onload=»myFunction»></element>

  • Использование window.onload

    Давайте попробуем создать эмуляцию window.onload, как это работает в реальном времени.

    Создадим скрипт и разместим его тут на странице:

    <script>

    window.onload = function() {

    alert(‘Страница загружена’);

    // к этому моменту страница загружена

    alert(`Image size: ${img.offsetWidth}x${img.offsetHeight}`);

    };

    </script>

    <img id=»img» src=»https://dwweb.ru/__a-data/__all_for_scripts/__examples/js/onload/onload.jpg»>

    Нажмите кнопку window.onload :

  • Использование (window).load JQuery

    Несколько вариантов для запуска вашего скрипта, при использовании JQuery

    $(window).load(function() {

    /** код запустится, когда страница будет полностью загружена на 100% **/

    });

    +

    //Вариант 1

    $(document).ready(function() {

    /** код запустится, когда будет готов DOM, исключая картинки **/

    // ваш код

    });

    //Вариант 2

    $(function() {

    /** код запустится, когда будет готов DOM, исключая картинки **/

    //ваш код

    });

    //Вариант 3

    $(document).on(‘ready’, function(){

    /** код запустится, когда будет готов DOM, исключая картинки **/

    //ваш код

    });

    //Вариант 4

    jQuery(document).ready(function(){

    /** код запустится, когда будет готов DOM, исключая картинки **/

    //ваш код

    });

    И!

    Не путаете window load jQuery с методом ajax load.

    Once upon a time, a confident student reassured Master Coffee that running Javascript on page load is very easy – Just add window.onload = FUNCTION. But the next day, the student asked Master Coffee why “my page is not working properly”. There’s more than meets the eye for the “simple on-page load”, read on.

    CODE DOWNLOAD

    I have released this under the MIT license, feel free to use it in your own project – Personal or commercial. Some form of credits will be nice though. 🙂

    VIDEO TUTORIAL

    1) WAYS TO RUN JAVASCRIPT ON PAGE LOAD

    1A) ON WINDOW LOAD

    1a-load.html

    // (PART A) ON WINDOW LOAD
    window.onload = () => {
      console.log("Loaded");
    };

    This is exactly the introduction snippet, just set window.onload = FUNCTION.

    P.S. () => { ... } is called an “arrow function”, a shorthand for function () { ... }

    1B) EVENT LISTENERS

    1a-load.html

    // (PART B) ADD EVENT LISTENER
    window.addEventListener("DOMContentLoaded", () => {
      console.log("On content load");
    });
    window.addEventListener("load", () => {
      console.log("On page load");
    });

    Next, is to set window.addEventListener(EVENT, FUNCTION).

    • load This is triggered when the page is fully loaded. That is, inclusive of all images, videos, audio, etc…
    • DOMContentLoaded This is triggered right before load. That is, some images, videos, and audio may not be fully loaded.

    P.S. There is a difference between window.addEventListener() and window.onload. We will go through that later.

    1C) DEFER LOADING

    1a-load.html

    <!-- (PART C) DEFER LOADING -->
    <script defer src="1b-load.js"></script>

    Set defer on the <script>. The browser will wait until the “main body and content” is done, then proceed to load this script.

    1D) PLACE THE SCRIPT AT THE BOTTOM

    1a-load.html

    <body>
      - PAGE CONTENT -
    
      <!-- (PART D) PLACE AT BOTTOM -->
      <script src="1c-load.js"></script>
    </body>

    Lastly, an old-school method. Just place the script at the bottom of the page, right before the closing </body>.

    2) THINGS TO LOOK OUT FOR

    2A) PROCESS ORDER

    Event listener, defer, on load, which one will launch first? With the above example:

    • 1c-load.js The script at the bottom of the page runs first.
    • 1b-load.js Followed by the deferred script.
    • DOMContentLoaded When the page and scripts are loaded.
    • window.onload and window.addEventListener("load") When the page is fully loaded.

    P.S. window.onload fires first, because we defined it before window.addEventListener("load").

    P.P.S. If we swap the order, window.addEventListener("load") will run before window.onload.

    2B) WINDOW ON LOAD WILL BE OVERRIDDEN

    2-beware.html

    // (PART A) ONLOAD
    // (A1) THIS WILL NOT RUN!
    window.onload = () => {
      console.log("Loaded");
    };
     
    // (A2) THIS WILL RUN INSTEAD
    window.onload = () => {
      console.log("Override");
    };

    As for why the student’s script “is not working” – There can only be one window.onload. If you define multiple window.onload, only the latest one will run.

    P.S. Try to use window.addEventListener("load") instead, there is technically no limit to how many scripts we can “prime” this way.

    2C) DEFERRED SCRIPT LOADING ORDER

    2-beware.html

    <!-- (PART C) DEFER LOADING -->
    <script defer src="1b-load.js"></script>
    <script defer src="1c-load.js"></script>

    If you define multiple deferred scripts, they will load in the exact order you defined them in – From top to bottom.

    • All “normal” <script> will load and run first.
    • Followed by 1b-load.js and 1c-load.js.

    THE END – INSERT SCRIPT ALTERNATIVE

    That’s all for this short tutorial. I hope this has helped you to solve the mystery of “properly run Javascript on page load”. Before we end, here’s one last alternative – Insert a script into the page after loading.

    window.addEventListener("load", () => {
      let script = document.createElement("script");
      script.src = "YOUR-SCRIPT.JS";
      script.async = true;
      document.head.append(script);
    });

    This is a roundabout method though, use this only when you have “no other choice” or working on a single-page app.

    CHEAT SHEET

    Load Javascript After Page Load (click to enlarge)

    Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии
  • Memory management windows 10 ошибка синий экран причины
  • Xiaomi утилита для windows
  • Clive barker s jericho не запускается на windows 10
  • Домашний сервер на windows server 2016
  • Как вырубить обновления на windows 10 навсегда