Javascript – ready vs on load event handler example

HTML document ready event is called before image assets, etc. are loaded on the page. window onload handler is called once all assets have been loaded. Few points to note when using jQuery:

  1. $(function() {});, $(document).ready(function(){}); or $(document).on("ready", function(){}); can be used to attach document ready event handler. Using multiple handlers is ok and additional handlers will not override old ones.
  2. $(window).load(function(){}); or $(window).on("load", function(){}); can be used to attach onload event handler. Using multiple handlers is ok and additional handlers will not override old ones.

Here is an example to show the sequence of document ready, image load, and window load handlers. Note that image load is called in between onready and onload handlers.

<html><head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head><body>
<img src="/img/elephant1_small.jpg" onload="img_onload();" />
<div id="log"></div>
<script type="text/javascript">
  function img_onload() {
    var old = $("#log").html();
    $("#log").html(old + "in img_onload<br/>");
  }
  $(function() {
    var old = $("#log").html();
    $("#log").html(old + "in ready handler<br/>");
  });
  $(window).load(function() {
    var old = $("#log").html();
    $("#log").html(old + "in load handler<br/>");
  });
</script>
</body></html>
refresh

Note that in case an image fails to load, window onload event handler is still called.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments