Test

How to run a function when the page is loaded?

Are you running window.onload = codeAddress after codeAddress() is defined? If so, this should work. Are you sure there isn’t an error elsewhere?

This doesn’t make any sense. window.onload runs after page load and all javascript is available, so the codeAddress() function can be declared anywhere within the page or linked js files. It doesn’t have to come before unless it were called during the page load itself.

@Jared Yes it does. Have a look at jsfiddle.net/HZHmc. It doesn’t work. But if you move the window.onload to after the definition: jsfiddle.net/HZHmc/1 it does work.

A function declaration is generally hoisted to the top of the scope, so the function can be declared anywhere in an accessible scope.

11 Answers 11

window.onload = codeAddress; should work — here’s a demo, and the full code:

       
     function codeAddress() 

As I said in my answer, there’s nothing wrong with the code as seen — the reason it’s not working must be an error in the JS somewhere.

the problem with this is that you may override previous onload functions. Use an event listener instead

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

Читайте также:  Kotlin flow collect all

I’d recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() < alert("Ready!"); >, false); 

@ᔕᖺᘎᕊ for the ‘bubbles’ property (which you do not have to include, I just fill in all booleans for good habit). There is also another boolean statement for ‘cancelable’ property, but it is not very useful since the above statement is already un-cancelable. Read more about it here: developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

This is what I was looking for right now 🙂 Executes when the DOM is complete, so you can manipulate it, not when the browser says «page completely loaded», which may take several seconds, based on external stuff (such as ads)

@x-yuri «The DOMContentLoaded event is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading (the load event can be used to detect a fully-loaded page).» — stackoverflow.com/questions/2414750/…

window.onload can only be set once. If you want to run two functions at load with window.onload , the second one will overwrite the first.

Alternate solution. I prefer this for the brevity and code simplicity.

This is an anonymous function, where the name is not specified. What happens here is that, the function is defined and executed together. Add this to the beginning or end of the body, depending on if it is to be executed before loading the page or soon after all the HTML elements are loaded.

This is the only code that works with HTML Preview for GitHub: htmlpreview.github.io Other code, while correct, is ruined by this HTML Preview.

Can someone explain how this is different than putting the script tags at the end of the HTML page and the purpose of the anonymous function?

@ChewieTheChorkie. The last line is as per the answer itself, because its an IIFE (Immediately Invoked Function Expression).

Taking Darin’s answer but jQuery style. (I know the user asked for javascript).

@VijayKumar this is jQuery, not native Javascript so you need a jQuery library included for it to work

This will likely work, but it will also break any other functions already hooking to that event. Or, if another function hooks into that event after yours, it will break yours. So, you can spend lots of hours later trying to figure out why something that was working isn’t anymore.

if(window.attachEvent) < window.attachEvent('onload', yourFunctionName); >else < if(window.onload) < var curronload = window.onload; var newonload = function(evt) < curronload(evt); yourFunctionName(evt); >; window.onload = newonload; > else < window.onload = yourFunctionName; >> 

Some code I have been using, I forget where I found it to give the author credit.

function my_function() < // whatever code I want to run after page load >if (window.attachEvent) else if (window.addEventListener) else
document.addEventListener('readystatechange', () => < if (document.readyState == 'complete') codeAddress(); >); 
  • loading — the document is loading (no fired in snippet)
  • interactive — the document is parsed, fired before DOMContentLoaded
  • complete — the document and resources are loaded, fired before window.onload
 document.addEventListener("DOMContentLoaded", () => < mydiv.innerHTML += `DOMContentLoaded (timestamp: $)
`; >); window.onload = () => < mydiv.innerHTML += `window.onload (timestamp: $)
` ; > ; document.addEventListener('readystatechange', () => < mydiv.innerHTML += `ReadyState: $(timestamp: $)
`; if (document.readyState == 'complete') codeAddress(); >); function codeAddress()

Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It’s basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.

// add reference to domReady script or place // contents of script before here function codeAddress() < >domReady(codeAddress); 

window.onload will work like this:

function codeAddress() < document.getElementById("test").innerHTML=Date(); >window.onload = codeAddress;

As soon as the page load the function will be ran:

document.onload = functionName(); window.onload = functionName(); 

I believe this is the best way to maintain support across different versions of browsers

if (window.addEventListener) < window.addEventListener("load", myFunction, false); >else if (window.attachEvent) < window.attachEvent("onload", myFunction); >else < window.onload = myFunction; //will override previously attached event listeners. >

Universal Cross-Browser Web Page Loader

I wrote a JavaScript page loader that should solve your issues loading a function after the page is loaded. This web page loader is 99.9% cross-browser compatible and works in many versions of browsers, old and new, unlike the other posts. Includes support for loading pages in nearly all browsers, including Internet Explorer 3-11, all Firefox and Chrome browsers, early Opera, all mobile browsers, Netscape 4 and 6 series, etc.

It will pick the fastest page load event or state check for a given browser and return a text string indicating JavaScript may safely process the Document Object Model (DOM). Should work in many legacy browsers, but test. Place your JavaScript functions or or library calls inside the «Start()» method below, so they are triggered as soon as the script says the web page or DOM is loaded in the browser.

As a side note, I recommend you place this code either:

  1. In the head of your html page in a embedded block as a synchronous script, which pauses the page to load early. . or.
  2. In a loaded external tag file with the «async» attribute added so it loads quietly in parallel to your page but pauses html loading when download complete so it gets parsed and processed first.

The script should not render-block much if using these methods. You want this script ready when the web page DOM is first built and not after, especially since later states of the page could get delayed waiting for images, videos, and JavaScript API’s to download.

 // ======== AFTER PAGE LOADS CALL YOUR SCRIPTS HERE ========= function Start(status) < // In most modern browsers the console should return: // "Browser Loader : Document : DOMContentLoaded : interactive" console.log(status); // add your script calls here. >; // ======== JAVASCRIPT PAGE LOADER ========= // Stokely Web Page loader, 2022 if (document.readyState) < if (document.readyState === "complete" || document.readyState === "loaded") < Start("Browser Loader : Document : readyState : complete"); >else < if (window.addEventListener) < // Never try and call 'DOMContentLoaded' unless the web page is still in an early loading state. if (document.readyState === 'loading' || document.readyState === 'uninitialized') < window.addEventListener('DOMContentLoaded', function () < // Most modern browsers will have the DOM ready after this state. if (document.readyState === "interactive") < Start("Browser Loader : Document : DOMContentLoaded : interactive"); >else if (document.readyState === "complete" || document.readyState === "loaded") < Start("Browser Loader : Document : DOMContentLoaded : complete"); >else < Start("Browser Loader : Document : DOMContentLoaded : load"); >>, false); > else < // FALLBACK LOADER : If the readyState is late or unknown, go ahead and try and wait for a full page load event. Note: This function below was required for Internet Explorer 9-10 to work because of non-support of some readyState values! IE 4-9 only supports a "readyState" of "complete". if (document.readyState === 'complete' || document.readyState === "loaded") < Start("Browser Loader : Document : readyState : complete"); >else < window.addEventListener('load', function () < Start('Browser Loader : Window : Event : load'); >, false); > > // If 'addEventListener' is not be supported in the browser, try the 'onreadystate' event. Some browsers like IE have poor support for 'addEventListener'. > else < // Note: document.onreadystatechange may have limited support in some browsers. if (document.onreadystatechange) < document.onreadystatechange = function () < if (document.readyState === "complete" || document.readyState === "loaded")< Start("Browser Loader : Document : onreadystatechange : complete"); >// OPTIONAL: Because several versions of Internet Explorer do not support "interactive" or get flagged poorly, avoid this call when possible. //else if (document.readyState === "interactive") < //Start("Browser Loader : Document : onreadystatechange : interactive"); //>> > else < // Note: Some browsers like IE 3-8 may need this more traditional version of the loading script if they fail to support "addeventlistener" or "onreadystate". "window.load" is a very old and very reliable page loader you should always fall back on. window.onload = function() < Start("Browser Loader : Window : window.onload (2)"); >; > > > > else < // LEGACY FALLBACK LOADER. If 'document.readyState' is not supported, use 'window.load'. It has wide support in very old browsers as well as all modern ones. Browsers Firefox 1-3.5, early Mozilla, Opera < 10.1, old Safari, and some IE browsers do not fully support 'readyState' or its values. "window.load" is a very old and very reliable page loader you should always fall back on. window.onload = function () < Start("Browser Loader : Window : window.onload (1)"); >; >; 

Note: When you run this script in a web browser, be sure to press F12 to pull up the browser tools screen and check the console tab to see the result. It will tell you at what stage the web page loader was triggered and when it called the ‘Start()’ script.

In most modern browsers (HTML5 or post-2010) it should be triggered as soon as the DOM or Document Object Model of HTML markup is rendered but the rest of the web page resources, CSS, images, video, and other files are still loading. In modern browsers this is usually between a readystate of «interactive» and «complete» and the DOM is built but the browser is still downloading other resource files. This allows your JavaScript to access and start manipulating the HTML tree or DOM very very early.

Older browsers like Internet Explorer v. 3-8 or Netscape, do not understand the advanced DOM checks so would require the full or «complete» load of the DOM and all page resources before calling your JavaScript.

Источник

Window: load event

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets, scripts, iframes, and images. This is in contrast to DOMContentLoaded , which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

This event is not cancelable and does not bubble.

Note: All events named load will not propagate to Window , even with bubbles initialized to true . To catch load events on the window , that load event must be dispatched directly to the window .

Note: The load event that is dispatched when the main document has loaded is dispatched on the window , but has two mutated properties: target is document , and path is undefined . These two properties are mutated due to legacy conformance.

Syntax

Use the event name in methods like addEventListener() , or set an event handler property.

addEventListener("load", (event) => >); onload = (event) => >; 

Event type

Examples

Log a message when the page is fully loaded:

.addEventListener("load", (event) =>  console.log("page is fully loaded"); >); 

The same, but using the onload event handler property:

.onload = (event) =>  console.log("page is fully loaded"); >; 

Live example

HTML

div class="controls"> button id="reload" type="button">Reloadbutton> div> div class="event-log"> label for="eventLog">Event log:label> textarea readonly class="event-log-contents" rows="8" cols="30" id="eventLog">textarea> div> 
body  display: grid; grid-template-areas: "control log"; > .controls  grid-area: control; display: flex; align-items: center; justify-content: center; > .event-log  grid-area: log; > .event-log-contents  resize: none; > label, button  display: block; > #reload  height: 2rem; > 

JavaScript

const log = document.querySelector(".event-log-contents"); const reload = document.querySelector("#reload"); reload.addEventListener("click", () =>  log.textContent = ""; setTimeout(() =>  window.location.reload(true); >, 200); >); window.addEventListener("load", (event) =>  log.textContent += "load\n"; >); document.addEventListener("readystatechange", (event) =>  log.textContent += `readystate: $document.readyState>\n`; >); document.addEventListener("DOMContentLoaded", (event) =>  log.textContent += `DOMContentLoaded\n`; >); 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 8, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

3 способа запуска функции или кода Javascript (js) при загрузке страницы.

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

Они пытаются взаимодействовать с HTML-элементами на странице, которые находятся ниже по коду, чем сам скрипт. Соответственно, скрипт уже подгрузился, а элемент, с которым нужно будет взаимодействовать, еще нет. По этой причине ничего работать не будет.

Особенность языка Javascript в том, что его код выполняется последовательно, строка за строкой, как они написаны в исходном коде.

    #block     К элементу с id #block не будет применяться правило css (background-color:yellow), т.к. строка
$("#block").css("background-color", "yellow");

Будет выполняться раньше, чем загрузиться html-строка:

 

Как быть, если нам нужно выполнить код или функцию, только после того, как весь документ полностью загрузится?

Я хочу рассказать о трех способах, как это можно сделать.

Все мои уроки по Javascript здесь.

1 способ. С использованием библиотеки jQuery.

Чаще всего сам им пользуюсь, наиболее простое и удобное решение, но требует подключения библиотеки Jquery.

Вот как преобразиться предыдущий, код, если мы воспользуемся следующим методом.

    #block      

2 способ. С помощью элемента body и атрибута onload.

    #block      Выбирайте тот способ, который более всего подходит к вашей ситуации, и применяйте его на практике.

Все мои уроки по Javascript здесь.

Источник

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