Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the earliest and latest events that jquery can hook into?

I've written a tiny plugin that gets the page load/render time. It collects the finish time at $(document).ready and I've put the code snippet that collects the start time right after the <title> tag.

I'd like this to be less obtrusive, so it seems there should be an earlier event than .ready where I can collect the earliest measurable page start time.

Here is the currently obtrusive javascript

<title></title>
<script type="text/javascript">
    var startTime = (new Date()).getTime();
</script>

Here is the plugin:

(function ($) {

    $(document).ready(function () {
        var endTime = (new Date()).getTime();
        var millisecondsLoading = endTime - startTime;

        $.get('hicmah.ashx?duration=' + millisecondsLoading, function (data) {
        });
    });

})(jQuery);
like image 211
MatthewMartin Avatar asked Nov 29 '11 14:11

MatthewMartin


People also ask

What is the jQuery method for attaching a custom event to an element?

bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.

What is an event and how event handled in jQuery?

Event methods trigger or attach a function to an event handler for the selected elements. The following table lists all the jQuery methods used to handle events. Method / Property. Description. bind()

Why is jQuery used to wire up events?

jQuery makes it straightforward to set up event-driven responses on page elements. These events are often triggered by the end user's interaction with the page, such as when text is entered into a form element or the mouse pointer is moved.


2 Answers

You can use onreadystatechange, DOMContentLoaded, and onload, which is what jQuery hooks into with the ready event shim.

if (document.addEventListener) {
  document.addEventListener('DOMContentLoaded', callback, false);
  window.addEventListener('load', callback, false);
} else {
  document.attachEvent('onreadystatechange', callback);
  window.attachEvent('onload', callback);
}

Alternatively, you could make sure that your page has a script tag at the top of the page, and at the bottom:

<html>
  <head>
    <script type="text/javascript">
      window.begin = new Date();
    </script>
    ...
  </head>
  <body>
    ...
    <script type="text/javascript">
      window.end = new Date();
    </script>
  </body>
</html>
like image 140
zzzzBov Avatar answered Nov 15 '22 00:11

zzzzBov


Having the plugin do this job is not possible because the plugin can be used anywhere on the page. The best way to achieve this is get the time right at the start of the html markup and right after the end of the html markup, it will give you the best time.

like image 37
ShankarSangoli Avatar answered Nov 14 '22 22:11

ShankarSangoli