32

I'm new to JavaScript.

I would like to call JavaScript / jQuery function after the page load in aspx page.

I tried using <form onload="function()"> and window.load = function(){}, but the JavaScript is still trigger before some of the content fully loaded.

Is it possible to call during Page_PreRender in aspx page and not in code behind, so that I can delay the JavaScript function ?

I tried setTimeout("function()",5000) to solve the problem.

However setTimeout() seem like is not compatible with some browser, e.g: caused looping in Google Chrome.

1
  • Does $(function(){}) not work for you?
    – ExtraGravy
    Apr 6, 2011 at 16:54

5 Answers 5

76

setTimeout is compatible with all browsers since 1996. You should avoid the evaluation of "functionName()" and instead do:

setTimeout(functionName,5000)

UPDATE: If you initially expect a variable passed to the function and none when in the timeout, you need to do this instead:

setTimeout(function() { functionName() },5000)

However you are calling the onload incorrectly, so you need to do either this:

window.addEventListener("load",function() {
  // your stuff
}

or the simpler

window.onload=function() {
  // your stuff
}

or, since you are using jQuery, this:

$(document).ready(function() {
    // your stuff
});

or just this:

$(function() {
    // your stuff
});
0
5

If you want to be 100% sure that it's when the page ACTUALLY loads, use:

$(window).load(function(){
   //After EVERYTHING loads, including images.
})

The other's solution, onload works, but it loads once the DOM is ready, but not when the window is actually finished loading.

3

If you're going to be using jQuery then it's preferable to attach an event to the document ready event using one of the following:

$(document).ready(callback);

or

$(document).ready(function () { /* do stuff */ });

or

$(callback);

or

$(function () { /* do stuff */ });
1
$(document).ready(function(){ 

   //Code goes here

});

or old style

<body onload="myFunction()">
3
  • 3
    we do not do Old Style any more - please.
    – mplungjan
    Apr 6, 2011 at 16:54
  • Okay, okay, I used it once when nothing else worked (IE6 + lot of scripts, long ago). And I don't like it too.
    – MadBender
    Apr 6, 2011 at 17:05
  • Old Style! kill it! burn it with a bat! smash it with fire! XP
    – ahnbizcad
    Nov 4, 2014 at 7:55
0

Would be best to use a framework like jQuery.
In jQuery you can define a function like this:

$(document).ready(function() {

});

This way it will be called when the DOM is fully loaded.

A full documentation of the ready() function can be found here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.