Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

jquery - How to delay calling of javascript function?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...