I have mentioned before that jQuery adds on a number of
usefully features to JavaScript that are meant to save time and make a
programmers life easier. One of the best examples I can personally think of is
the jQuery.ready() function. The ready() function runs your code after the DOM
has been loaded and is ‘ready’ to access and manipulate. Although this may
sound like a simple and useful thing to do, pure JavaScript does not have an
equivalent. While JavaScript has some alternatives, they are limited by browser
capability and do not accomplish the task with the same level of sophistication
as jQuery. The jQuery API itself mentions a JavaScript alternative while
pointing out its shortcomings. The API
states “While JavaScript provides the load event for executing code when a page
is rendered, this event does not get triggered until all assets such as images
have been completely received. In most cases, the script can be run as soon as
the DOM hierarchy has been fully constructed.” (https://api.jquery.com/ready/).
Continuing an example I have used throughout the course of this blog, I would
like to share an experience where .ready() was extremely useful to me.
The web app I recently developed for Company B relied
heavily on manipulating DOM elements. Since I was able to use jQuery I just
threw the necessary code in the method and didn’t really think much of it.
However, I think we should take time now to examine just how cumbersome the
alternative would have been. As a disclaimer I will state that the purpose of
this blog is not to re-implement the jQuery.ready() method – there are a number
of people who have done that already so we will rely on their experience. Stackoverflow
user jfriend00
provided an alternative to the jQuery .ready() function as an answer to a
question posted on the forum. His answer can be found here: http://stackoverflow.com/a/9899701
Here is the jsFiddle that jfriend00 posted with his working
alternative:
*Again, just as a note I did not write this jsFiddle unlike
the others on this blog.*
So while some others may suggest that there are easy ways to
work around JavaScripts lack of a .ready() function, it is clear that there is
a large amount of detail in the actual implementation of the method. This is a
specific example of a time that jQuery made it much easier for me to do a
simple task. If during my implementation of the web app I did not have access
to jQuery then I could have run into an issue with trying to access elements
from the DOM that had not been loaded yet.
No comments:
Post a Comment