chaosguru
chaosguru

Reputation: 1983

Run JavaScript after every time page is loaded

I have a simple question but its haunting me since many days and I couldn't find the solution. I would like to fire a JavaScript event for every time the page is loaded or rendered.

Can any body please help?

Upvotes: 0

Views: 11583

Answers (4)

Arj
Arj

Reputation: 2046

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.

Upvotes: 4

optimusprime619
optimusprime619

Reputation: 764

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

Upvotes: 0

ravi404
ravi404

Reputation: 7309

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

Upvotes: 4

JMax
JMax

Reputation: 26591

you can use <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?

[EDIT] or better (?), use:

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

(from this thread)

Upvotes: 5

Related Questions