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
270 views
in Technique[技术] by (71.8m points)

javascript - Trigger event on body load complete js/jquery

I want to trigger one event on page load complete using javascript/jquery.

Is there any way to trigger event or call a simple function once page loading fully completes.

Please suggest folks if you any reference.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Everyone's mentioned the ready function (and its shortcuts), but even earlier than that, you can just put code in a script tag just before the closing body tag (this is what the YUI and Google Closure folks recommend), like this:

<script type='text/javascript'>
pageLoad();
</script>
</body>

At this point, everything above that script tag is available in the DOM.

So your options in order of occurrence:

  1. Earliest: Function call in script tag just before closing the body tag. The DOM is ready at this point (according to the Google Closure folks, and they should know; I've also tested it on a bunch of browsers).

  2. Earlyish: the jQuery.ready callback (and its shortcut forms).

  3. Late, after all page elements including images are fully loaded: window onload event.

Here's a live example: http://jsbin.com/icazi4, relevant extract:

</body>
<script type='text/javascript'>
  runPage();

  jQuery(function() {
    display("From <tt>jQuery.ready</tt> callback.");
  });

  $(window).load(function() {
    display("From <tt>window.onload</tt> callback.");
  });

  function runPage() {
    display("From function call at end of <tt>body</tt> tag.");
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
  }
</script>

(Yes, I could have used jQuery for the display function, but I was starting with a non-jQuery template.)


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

...