Don't Initialize All the Things in jQuery.ready()
One of the first impressions a user gets is loading your web application for the first time. Users don't have a high tolerance when it comes to page speed. They want to see something almost immediately and then be able to start interacting with your web site shortly after.
The following examples will show two ways of initializing a date picker. The first way will "Initialize All the Things" and the other example will use the "Just-In-Time Initialize" principle.
In order to convey the idea I'm trying to explain it is probably easiest to show a code sample and then talk about what is happening. We will be using the following HTML for the markup that our code examples will be using.
I am using Twitter Bootstrap to made the UI look more presentable and that is why you are seeing some extra classes attached to the above markup.
The markup shows a simple form with various input elements. In the form we will have multiple date fields that we will want to initialize using the jQuery UI
Initialize All the Things
jQuery code looks familiar to many snippets that you'll might find across the internet, in tutorials, and possibly in your web applications.
I am using the small moment.js library to help with data manipulation. It is a handy date library that I think you'll find very compelling and rich with features.
Let's unravel what the code is doing...
- We wait until the document is ready before running the rest of our code.
- Once the DOM is ready, then select all the
inputelements on the page with the
- jQuery will implicitly iterate over it's internal collection of elements and initialize each one with the
datapickerjQuery UI widget.
Pros of this Technique
- When the user interacts with any of the
input.dateelements they will already be setup and therefore will respond extremely quick.
Cons of this Technique
- Your code has to wait until the DOM is ready before it can select the elements. It would be nice if you could utilize the time between when jQuery is executed and when the DOM is ready.
- The selector doesn't have any context so it is looking throughout the whole DOM looking for
inputelements with the
dateclass. This would be considered a sub-optimal selector since there is no limit to the scope or context of what is being searched.
- The code is initializing all the elements (implicit loop) whether you need them or not. Sure, the widgets are ready when you need them, but is all that up front code necessary?
- There is quite a bit of extra code running that isn't necessary yet before the page has even fully loaded. The affects the overall User Experience of page load, which is very key concern to users.
The following code snippet looks considerably different from the previous example, but the end result is the same and the Pros and Cons are quite different. See if you can spot out the differences.
You can view, run, and edit the above code sample from JsFiddle or you can interact with the embedded version below.
I am using the toastr library to show messages indicating when the elements were initialized. This library was created by Hans Fjällemark and John Papa.
As we did in the previous example let's outline what is happening in the code and then we will examine the Pros and Cons of this technique.
- We immediately set up an event handler to wait for User Input before initializing the
datepicker. This allows the code to run immediately after
jQueryhas been executed on the page before the DOM is even ready. We don't need the DOM to be ready because we are delegating our event to the
- We aren't initializing all the
input.dateelement, but are only listening to the
focusevent. This event will propagate (a.k.a. bubble) up the DOM tree until it gets to the
documentat which point jQuery will determine if the item focused on matches any of the metadata it has stored. This metadata match is surprisingly fast because it is only matching this "crazy" selector against the one DOM element that was focused on and not the whole DOM tree.
- Our advanced selector is looking for
input.dateelement that doesn't have the
hasDatepickerclass. If this is a match then that one DOM element will be initialized. After that point, if the element is focused on later the selector will no longer be a match because jQuery added the
hasDatepickerclass during the it's widget creation.
Pros of this Technique
- Very fast page load speed because you are only adding an event handler to the
documentwith some metadata that will be used later
- There is no jQuery selection being made on DOM ready
- There is no implicit looping going on to initialize the elements
- Only the elements that are about to be used are initialized so there is no wasteful code being executed
- The focused elements are only initialized once
- This technique will also work for dynamically added date pickers added to the DOM
Cons of this Technique
- There is some overhead of the focus event having to propagate up to the
jQuerycheck the metadata to see if there are any matching selectors for the element in question, but this is mostly a wash since it is only testing one element.
You want to limit initializing all the things all the time. It can be helpful if you start to think about delaying initialization until the point when you need it or possibly right before. By doing so you can utilize the time right after jQuery is executed and not wait for DOM ready then you are able to use that precious time during page load. In addition you can have a crazy weird jQuery selector that still is fast. In our last code example above had a complicated selector, but it was very fast because it is only being tested against the one element that was focused on and not the whole DOM tree.
Much of this material was gleaned from an awesome series Doug Neiner has given at the past several jQuery Conferences entitled "Contextual jQuery" (video & slides). If you haven't already seen his talks or slides I highly encourage you to go through them.