Mythrillic
Mythrillic

Reputation: 417

run javascript functions when the page loads

I have several JavaScript functions that need to run when the page loads to fetch content. I have tried to use window.onload to call the function but it hasn't worked.

Basically, need to run several functions after the page finishes loading but only once.

I have this so far but it didn't work

<script language="javascript">
window.onload=serverstats
window.onload=latestnews
</script>

Upvotes: 1

Views: 146

Answers (3)

Drew Galbraith
Drew Galbraith

Reputation: 2256

You can also handle both by using the following code:

window.addEventListener("load", serverstats);
window.addEventListener("load", latestnews);

This doesn't work in IE8 and earlier though, which use:

window.attachEvent("onload", serverstats);
window.attachEvent("onload", latestnews);

Upvotes: 1

Gazler
Gazler

Reputation: 84150

Here is your main issue:

window.onload=serverstats  #sets window.onload to serverstats
window.onload=latestnews   #sets window.onload to latestnews and removes the reference to serverstats

You can fix this by doing:

oldOnload = window.onload;
window.onload=function() {
    oldOnload();
    serverstats();
    latestnews();
};

However, as the question is tagged with JQuery, I would recommend using it and doing:

$(document).ready(function() {
    serverstats();
    latestnews();
});

Upvotes: 4

Samir Talwar
Samir Talwar

Reputation: 14330

You're overwriting the onload value. Write a function that calls both of them instead.

window.onload = function() {
    serverstats();
    latestnews();
};

Upvotes: 0

Related Questions