简体   繁体   中英

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>

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();
});

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);

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM