How to Run a Function When the Page Is Loaded

How to run a function when the page is loaded?

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

<!DOCTYPE html><html>    <head>        <title>Test</title>        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />        <script type="text/javascript">        function codeAddress() {            alert('ok');        }        window.onload = codeAddress;        </script>    </head>    <body>        </body></html>

How do I call a JavaScript function on page load?

If you want the onload method to take parameters, you can do something similar to this:

window.onload = function() {
yourFunction(param1, param2);
};

This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

How to execute a function when page has fully loaded?

That's called load. It came waaaaay before DOM ready was around, and DOM ready was actually created for the exact reason that load waited on images.

window.addEventListener('load', function () {
alert("It's loaded!")
})

How to make JavaScript execute after page load?

These solutions will work:

As mentioned in comments use defer:

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

or

<body onload="script();">

or

document.onload = function ...

or even

window.onload = function ...

Note that the last option is a better way to go since it is unobstrusive and is considered more standard.

How do I automatically run a function when the page is loaded?

ngOnInit() is the right place, when you want to call the method onload. If the data is async 'selected' can still be undefined when the template is rendered. To avoid the error you can wrap the block with a condition like @Flignats did or simply add a ? like

  <h1>{{selected?.title}}</h1>
{{selected?.person_id}}

The ?. stops evaluating when selected is null or undefined.

You are assigning the data outside the subscription. It should be like this:

getData(){
...
this.http.get(url).subscribe(data => {
this.data = data;
this.selected=this.data.find(item=>
{
if(item['person_id']===person_id)
{
return true;
}
return false;
});
console.log(person_id, this.selected);
});
}

How to run a function everytime the page loads in React

You can use useState hook and store the values of the page dimensions and make use of the useEffect hook to run a function everytime the page loads or the state changes

const [dimensions, setDimensions] = useState(pageDimensions)

useEffect(() => {
// the function you want to call
}, [dimensions])

So the flow is - you first have to calculate the page's dimensions and set it as the initial value of the state. Then whatever function you want to call everytime the page loads or resizes, write in inside the useEffect hook function. And finally make another function or use useEffect where you can check whenever the page resizes so that you can set the state to the new dimensions.

Execute JS function after some time of page load

Use setTimeout instead, as it is called only once after the pause:

setTimeout(myFunc, 3000);

How can I execute a JavaScript function on the first page load?

The code below will execute once the onload event fires. The statement checks if the onetime function has NOT been executed before by making use of a flag (hasCodeRunBefore), which is then stored in localStorage.

window.onload = function () {
if (localStorage.getItem("hasCodeRunBefore") === null) {
/** Your code here. **/
localStorage.setItem("hasCodeRunBefore", true);
}
}

Note: If the user clears their browsers' localStorage by any means, then the function will run again because the flag (hasCodeRunBefore) will have been removed.

Good news...

Using localStorage can be tedious because of operators and long winded function names. I created a basic module to simplify this, so the above code would be replaced with:

window.onload = function () {
if (!ls.exists('has_code_run_before')) {
/** Your code here... **/
ls.set.single('has_code_run_before', true);

/** or... you can use a callback. **/
ls.set.single('has_code_run_before', true, function () {
/** Your code here... **/
});
}
};

Update #1

Per @PatrickRoberts comment, you can use the in operator to see if a variable key exists in localStorage, so

if (localStorage.getItem('hasCodeRunBefore') === null)

becomes

if (!('hasCodeRunBefore' in localStorage))

and is less verbose and a lot cleaner.

Secondly, you can set values as you would an object (localStorage.hasCodeRunBefore = true) though it will be stored as a string, not as boolean (or whatever data type your value is).

call function after complete page load

Most likely you're getting a value of 0 because you're printing the information before the page has completed loading, try the following snippet:

window.onload = function(){
setTimeout(function(){
var t = performance.timing;
console.log(t.loadEventEnd - t.responseEnd);
}, 0);
}

That will make sure the numbers are printed after the page is actually ready. Got that snippet from here. Other information from that page you might find interesting:

Data from the API really comes to life when events are used in combination:

  • Network latency (): responseEnd-fetchStart.
  • The time taken for page load once the page is received from the server: loadEventEnd-responseEnd.
  • The whole process of navigation and page load: loadEventEnd-navigationStart.


Related Topics



Leave a reply



Submit