简体   繁体   English

页面加载时运行javascript函数

[英]run javascript functions when the page loads

I have several JavaScript functions that need to run when the page loads to fetch content. 页面加载以获取内容时,我需要运行一些JavaScript函数。 I have tried to use window.onload to call the function but it hasn't worked. 我试图使用window.onload来调用该函数,但是它没有起作用。

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: 但是,由于问题是用JQuery标记的,因此我建议使用它并执行以下操作:

$(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: 这在IE8和更早版本中不起作用,但使用:

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

You're overwriting the onload value. 您正在覆盖onload值。 Write a function that calls both of them instead. 编写一个调用它们两者的函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 页面加载时会调用哪些JavaScript函数? - Which JavaScript functions are called when page loads? 加载外部页面时运行javascript以在Firefox中对其进行操作 - Run javascript when foreign page loads to manipulate it in firefox jQuery Mobile页面加载时运行Javascript函数 - Run Javascript function when jquery mobile page loads 页面加载后,如何在Chrome中运行JavaScript代码段? - How can I run JavaScript snippets in Chrome when the page loads? 页面动态加载内容时如何运行javascript函数 - How to run a javascript function when a page dynamically loads content javascript-页面加载后立即运行chrome扩展 - javascript - run chrome extension as soon as page loads 如何在页面加载时停止javascript中的警报触发,并在单击按钮时使其运行? - How can I stop an alert in javascript from firing when the page loads, and make it run when a button is clicked? 部分加载时运行Javascript / Jquery - Run Javascript/Jquery when partial loads 在ASP.net页面加载时以编程方式运行javascript的最佳方法是什么? - What is the best way to programmatically run javascript when an ASP.net page loads? 页面加载时需要从单选列表中获取价值并运行javascript函数 - Need to get value from radiolist and run javascript function when page loads
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM