palAlaa
palAlaa

Reputation: 9858

How do I call a JavaScript function on page load?

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)

<body onload="foo()">

When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.

Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

Upvotes: 388

Views: 1548408

Answers (9)

greenie-beans
greenie-beans

Reputation: 510

here's an example with es6 and no jquery:

window.onload = () => {
  foo()
}

see the mdn docs: https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

Upvotes: 4

STW
STW

Reputation: 46366

Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply

The typical options is using the onload event:

<body onload="javascript:SomeFunction()">
....

You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.

<body>
  ...
  <script type="text/javascript">
    SomeFunction();
  </script>
</body>

Another option is to use a JS framework which intrinsically does this:

// jQuery
$(document).ready( function () {
  SomeFunction();
});

Upvotes: 74

Ahmed Jolani
Ahmed Jolani

Reputation: 3072

Another way to do this is by using event listeners, here's how you use them:

document.addEventListener("DOMContentLoaded", function() {
  your_function(...);
});

Explanation:

DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...

function() Anonymous function, will be invoked when the event occurs.

Upvotes: 160

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92377

For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use

let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
  if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });


// TEST: simulate element loading
let tmp=1;
function loadContent(name) {  
  setTimeout(()=>{
    console.log(`Element ${name} loaded`)
    content.innerHTML += `<div>My name is ${name}</div>`; 
  },1500*tmp++)
}; 

loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

Upvotes: 1

Amir Md Amiruzzaman
Amir Md Amiruzzaman

Reputation: 2079

You have to call the function you want to be called on load (i.e., load of the document/page). For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.

Try the code below:

<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function () {
        yourFunction();
    });
    function yourFunction(){
      //some code
    }
</script>

Upvotes: 8

anonymous
anonymous

Reputation: 157

<!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>

Upvotes: 14

Abhishek
Abhishek

Reputation: 664

here's the trick (works everywhere):

r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

Upvotes: 6

Sarfraz
Sarfraz

Reputation: 382696

function yourfunction() { /* do stuff on page load */ }

window.onload = yourfunction;

Or with jQuery if you want:

$(function(){
   yourfunction();
});

If you want to call more than one function on page load, take a look at this article for more information:

Upvotes: 53

Matt Sieker
Matt Sieker

Reputation: 9635

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.

Upvotes: 585

Related Questions