简体   繁体   English

每次页面加载后运行javascript

[英]run javascript after everytime page is loaded

I have a simple question but its haunting me since many days and i couldnt find the solution. 我有一个简单的问题,但由于困扰了我很多天,所以找不到解决方案。 I would like to fire a javascript event for everytime the page is loaded or rendered. 我想在每次页面加载或渲染时触发一个javascript事件。

can any body please help. 任何人都可以帮忙。

you can use <BODY onLoad="alert('hello world!')"> 您可以使用<BODY onLoad="alert('hello world!')">

See some drawbacks and workaround on this thread: Is there a cross-browser onload event when clicking the back button? 请参见此线程的一些缺点和解决方法: 单击“后退”按钮时是否存在跨浏览器的onload事件?

[EDIT] or better (?), use: [编辑]或更高(?),请使用:

window.onload=function() { 
   alert ('hello world');
}; 

(from this thread ) (从此线程

window.onload = function(){/*your code*/}

Try using this: 尝试使用此:

<html>
    <head>
        <script type="text/javascript">

            function function_name() {
               alert('loaded');
            }

        </script>
    </head>

    <body onload="function_name()">
        <p>hello</p>
    </body>

</html>

Although the best way would probably be to use jQuery's ready() function to ensure browser compatibility. 尽管最好的方法可能是使用jQuery的ready()函数来确保浏览器兼容性。

if your reqirement is such that the script needs to execute after the page has loaded completely you could write it in the following way 如果您的要求是在页面完全加载后需要执行脚本,则可以通过以下方式编写脚本

$(window).bind('load',function(){
    //your code here
});

document.ready works when the page html elements are loaded... the above code executes after the entire page (with its styling and images etc.) hence i believe that this requires a seperate mention 当页面html元素被加载时document.ready可以工作...上面的代码在整个页面(带有样式和图像等)之后执行,因此我认为这需要另外提及

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

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