What is Jquery and why use Jquery (Best Tutorial 2019)

What is Jquery

What is jQuery

jQuery is a JavaScript library. This means that it's a collection of reusable JavaScript code that accomplishes common tasks. Since web developers often find themselves solving the same problems over and over again, it makes sense to collect useful bits of code into a single package that can be included and used in any project.

 

The creators of jQuery have written code to smoothly and easily handle the most common and most tedious tasks we want to accomplish with JavaScript, and they've ironed out all the little differences that need to be worked out to get the code working in different browsers.

 

Why Have We Been Using jQuery

Simplicity

jQuery’s API is intuitive. Want to add a CSS class to an element? Just use the addClass() method. Need to send a POST request? Just use the post() method. And hiding an element is as simple as passing it as a parameter into jQuery’s hide() method. 

 

The magic of jQuery is evident in its dirt-simple API. It allows those who have little prior knowledge of the browser or JavaScript to create something intriguing and useful.

 

This is quite appealing and arguably even most appropriate for those who only dabble in web development. Conversely, the simplicity of jQuery is also a potential hazard for professional web developers. If you do not already believe this to be true, we will explore this theory a bit later on.

 

Community

why use Jquery

On Stack Overflow, 1.2 million questions are tagged as JavaScript questions, and 750,000 are tagged as jQuery questions. jQuery is the 6th-most popular tag on Stack Overflow.

 

The next most popular front-end library is AngularJS in a distant 21st place, which only has 200,000 tagged questions. Interestingly, 200,000 questions are tagged as jQuery and not JavaScript. In many cases, jQuery is not seen as a JavaScript library.

 

In fact, it is seen as an alternative to JavaScript. A way to address the browser without having to ever deal with the underlying language or API. While the relation to JavaScript may not be clear to some, jQuery has no shortage of developers willing and ready to offer advice on the library.

 

Of the 750,000 jQuery-tagged questions on Stack Overflow, 550,000 (74%) contained at least one upvoted answer.

 

As of mid-2016, jQuery is still the most used JavaScript library in public websites. In fact, 70% of all public websites depend on jQuery in some way. 2 The next most popular library is Bootstrap, which is only used in 13% of all public sites. With this impressive market share, there is certainly a fair share of users with some working knowledge of the topic.

 

In addition to the jQuery tag on Stack Overflow and the wealth of different forums and sites dedicated to advising those invested in the technology, jQuery’s site has its own active user forums.

 

Habit

habit

A large number of examples, blog posts, and forums aimed at jQuery beginners is one of the reasons why those new to web development choose this library to assist with their project. But what about seasoned developers? Why do they continue to use jQuery in their projects?

 

A polished, experienced developer was once an amateur. As amateurs, they may very well have embraced jQuery. Now, with multiple projects under their belt, jQuery has proven itself. And even if some of the flaws in the library have been noticed, they are well understood.

 

To a seasoned developer, jQuery is consistent and reliable enough. It has become part of the development process. A strong community is a benefit realized by experienced developers as well, and this is yet another reason to stick with such a trustworthy tool.

 

jQuery has been a prerequisite for everything we write. We mindlessly import it, partially because we have been trained, out of habit, to do so. We have been trained to think that this is a vital component of every web application. Habits are hard to break, especially those that have produced positive results.

 

Software development can be stressful and frustrating. A typical developer wrestles with a seemingly infinite number of variables on a daily basis. No problem, it seems, is simple to solve.

 

Consistency and predictability of a tool, process, or outcome is highly desired and rare. Can you blame the web development community for relying on a consistent and reliable tool like jQuery for so long?

 

Elegance

Have you ever heard anyone claim that the DOM is ugly or JavaScript is flawed and riddled with time bombs? Perhaps you think this yourself. While beauty is mostly subjective, this seems to be a surprisingly common thought, especially among more seasoned developers who continue to use jQuery late into their web development career.

 

The oft-perceived lack of elegance in the native browser API and JavaScript ostensibly drives developers to this library, among other things. The thought is that simple problems are difficult to solve without the aid of jQuery. Don’t believe me? Ask some of the developers you work with. Why do they use jQuery?

 

Expect to hear about how simple it is to create elegant and terse code in response to common problems. As discussed earlier in this section, the API itself is intuitive and elegant.

 

But the elegance of jQuery is more than simply a predictable API. The usability considerations surrounding the design of the API further this claim of elegance.

 

Take method chaining, for example, which allows a developer to very easily tie together a number of operations on the same element or elements without the burden of repetition or temporary variable creation.

 

Suppose you want to select a set of elements, then add a class to all of them, and finally add a class to an even more specific subset of the initial set of elements.

 

You can do all of this very easily by harnessing the elegance of method chaining provided by jQuery’s API. Listing 1-1 demonstrates this by adding a class of “underline” to all elements that contain a class of “alphabet”.

 

It then selects only child elements of “alphabet” elements that contain a class of “vowels” and finally annotates them with a class of “bold” while hiding any child of “vowels” elements that themselves also contain a class of “a”:

 jQuery method chaining

$('.alphabet').addClass('underline')

.find('.vowels').addClass('bold')

.find('.a').hide();

 

I have found that many developers tend to struggle with asynchronous operations in JavaScript, such as AJAX requests. Making these requests is not difficult, but dealing with the result, given the asynchronous nature of the call, proves to be frustrating for some.

 

jQuery simplifies this a bit by allowing a response handling function to be elegantly tied to the function call that sends the underlying request. Listing 1-2 sends a request to retrieve a user’s name, providing simple access to the result from the server’s response.

 style="margin:0;width:899px;height:125px">Listing 1-2. jQuery GET request

$.get('name/123', function(theName) {

console.log(theName);

});

 

Note The console object is not available in Internet Explorer 9 and older unless the developer tools are open. Also, the preceding example does not handle error responses, only success.

 

With all this “beauty,” it’s easy to forget about other attributes of our efforts, such as performance. Are there potential efficiency of landmines in the previous examples? Yes, but these may be tough to identify initially. I discuss this more in a later blog.

 

Fear

jQuery web development

jQuery makes everything easier—web development is hard. You can’t develop a solid web application or library without some help. It’s far too difficult to ensure your app will work properly in all browsers without jQuery.

 

The web API implementation varies wildly between browsers. All the good plug-ins you need depend on jQuery anyway.

 

These are all common excuses for blindly depending on jQuery, and they are all based on fear. We have all relied on jQuery due to fear of the unknown. We see the DOM as a mysterious and unpredictable black box, littered with serious bugs. We fear cross-browser implementation variances.

 

The creator of jQuery, John Resig, famously concluded that “The DOM is a mess” back in 2009. At that moment in web history, Internet Explorer 6 and 7 accounted for almost 60% of the browser market.

 

With this in mind, it’s hard to argue with Mr. Resig’s statement at the time. The DOM was indeed a scary and fickle beast, and the most popular browsers of the day had very poor and limited built-in tools.

 

What if we look even further back, to August 2006, when jQuery was created and first released? At that time, the newest version of Internet Explorer was version 6. IE6 (and older) accounted for an incredible 83% of all browsers in use.

 

At this point, the web API was exceptionally immature, the stability of browsers was much lower than we have come to expect in the current era, and standards compliance was quite inconsistent across the browsers of the time.

 

In addition to immature developer tools, varying web API implementations, and the unintuitive DOM, browsers can certainly be buggy. Similar to any other complex bundle of code, browsers are not immune from bugs.

 

jQuery has historically promised a wide range of browser bug workarounds. For many years, the web seemed to be akin to the Wild West in terms of standards observance and quality control.

 

It’s not hard to see why a library that aims to normalize the browser landscape was so popular. No need to fear cross-browser support anymore. No need to even worry about cross-browser testing. jQuery will do all of the heavy liftings for you, so you can focus entirely on developing intriguing and useful web applications and libraries. Or can you?

 

While the hope is that jQuery will free you from all of the problems and complexities baked into the browser, the reality is a bit different.

 

[Note: You can free download the complete Office 365 and Office 2019 com setup Guide for here]

 

A Crutch Is Only Temporary

JavaScript libraries

JavaScript libraries are often useful tools. They assist in your efforts to architect a useful and reliable web application, or perhaps even another library. They save you time and keystrokes. They serve as a buffer between you, your code, and the browser, filling in the gaps and normalizing behavior.

 

In another sense, these libraries can function as crutches. They help inexperienced and uneducated developers, without actually teaching them anything about the underlying complexity.

 

Even though the tone of this blog may at times suggest otherwise, libraries like jQuery are not inherently bad. They are only limiting if your learning does not progress beyond the library.

 

Does jQuery always save you time? Is it always making your web development experience easier? Are the conventions associated with the core library or its plug-ins intuitive?

 

Does it really solve all of your problems, or does it perhaps create some new ones? Have you taken the time to ponder the syntax and conventions that come with the library?

 

Is there a better solution, or does jQuery really patch all of the usability holes that developers often fall into? Mostly, jQuery’s API is pleasing to the eye and remarkably intuitive.

 

But of course, this is not true all of the time. There are certainly parts of the library that are unpleasant. Let us example the elegance and necessity of jQuery a bit.

 

jQuery does not completely shield you from the browser’s quirks. This is not a realistic goal of any library. Aside from this, jQuery is simply a library, a tool, an aid. It isn’t meant to replace the entire browser stack. Some problems are even best solved with CSS or static HTML.

 

But to the developer using jQuery as a crutch, it is the only way to interface with the browser. To the uninformed developer, it is perfectly reasonable to write minimal HTML and make any and all adjustments to markup using jQuery’s API.

 

Or perhaps it would be even easier to generate all markup using jQuery. You can create elements with jQuery, and then easily insert them onto the page.

 

Instead of declaring styles in CSS filesthe inclination is to use $(element).css('font-weight', 'bold'). While very convenient, this is a horribly unmaintainable method of generating inline styles. The importance of separation of concerns may not be readily apparent to the new developer.

 

The magical all-encompassing API of jQuery makes it easy to ignore the native tools available to us. The appropriate roles of HTML, CSS, and JavaScript do not always enter into the equation when you are blindly depending on a monolithic abstraction.

 

This library is not just a tool for some, it is the tool. It is the be-all and end-all of web development. You’ll see why this is a dangerous line of thinking, especially for professional and aspiring developers.

 

Indeed, jQuery is a crutch for many. It is not fused to the browser and merely acts as a supplement. Experienced and knowledgeable developers may actually prefer to use jQuery, and there is certainly nothing wrong with that.

 

But for others, it serves as a prop. Those new to the world of web development often pick up this crutch and hobble along for quite some time. But eventually, the crutch is pulled out from under them, and they fall.

 

You Are a Mechanic, Not a Driver

 learn JavaScript before learning jQuery

A popular question on Stack Overflow asks “Is it a good idea to learn JavaScript before learning jQuery?” One particular answer to this question provides some curious advice.

 

The contributor goes on to say in his answer “You really don’t need to focus too much on learning the ins and outs of the HTML DOM if you are going to use a framework like jQuery. Just do things the ‘jQuery way’ and then pick up as much HTML DOM as is necessary along the way.”

 

Though this line of thinking is apparently not common among others who contributed answers to this question (perhaps more experienced developers). I myself was a new and inexperienced web developer at one point and remember how this train of thought was embraced by those entering the confusing world of browser-based front-end coding.

 

In other words, for a stable, long-lasting application or library, you must have a good understanding of exactly how your tools work. Short of this, you are not a developer. You are, in fact, a library integrator.

 

Can we compare driving a car to drive the browser? As software developers, do we really need to understand the underpinnings of the web? As you saw in the above Stack Overflow answer, some may say no. But it’s important to understand that we are not drivers. We are mechanics and designers, not users.

 

Stunted Growth

Stunted Growth

What happens when you are thrust into a new project without jQuery, without your crutch? If your capabilities stop at the edge of the library’s API, your options are limited. You’re very much invested in this abstraction, jeopardizing your ability to grow beyond it.

 

Do you really want to be dependent on a single chunk of code for all of your projects? In the short term, this doesn’t seem like a problem. Looking forward, the feasibility of this path becomes questionable.

 

The landscape of software development, and technology in general is constantly changing. As developers, we not only understand this, we embrace it. This makes our jobs both challenging and interesting.

 

There’s nothing wrong with using jQuery, or any other library. But by using these as a crutch, we cease to be software developers. We are jQuery programmers.

 

As a new developer, your goals shouldn’t necessarily revolve around agility. Learning the fundamentals at this early stage is paramount. By becoming comfortable with your environment—the browser—you put yourself in a better position to make good decisions as your project and career evolve.

 

Only after you have a firm grasp of the fundamentals and a better understanding of web development in its most basic form should you focus on choosing and learning a tool to speed up your development process.

 

This advice is really not specific to software development. Do you remember back when you were first learning math? All the exercises you completed could have easily be solved using a calculator. Most likely, you were strictly forbidden from using a calculator, though (I know I was). Why? Calculators are faster and more accurate.

 

Simply put, in this stage, the aim is not to speed. A thorough understanding of the fundamentals—of math—is most important. Once you understand how the calculator performs these tasks, you can choose to use one, or not, as you solve more complex problems in the future. Understanding the fundamentals ensures you are not chained to a tool.

 

When our library of choice fades into obsolescence or is otherwise pulled out from under us, our blind reliance prevents us from moving forward. Examples of this unfortunate situation are readily available.

 

In a fairly recent article in JavaWorld, the author cites “6 reasons you should be using jQuery.” The reasons are questionable as the author clearly is missing even a basic understanding of the browser stack.

 

This is particularly evident in claims such as “jQuery is a major component of HTML5,” conflating JavaScript with a document markup specification. Another troubling quote from this article: “jQuery pages load faster.” It’s this type of oversimplification that leads us, as developers, to take the complexity of our jobs for granted.

 

By pretending that a beast like a browser can be tamed with a single library just opens us up to a frustrating struggle that we will eventually lose.

 

The Price of Shortcuts (a True Story)

web developer

What follows is a real story of a real web developer who took real shortcuts (really). He only focused on the short term, on making his job easier. His main concern was pleasing project managers.

 

Learning the fundamentals was a waste of time to him. Churning out the code and plowing through a long list of features as quickly as possible was his goal. That developer was me.

 

jQuery makes everything easier. You can’t develop a solid web app without it. It’s far too difficult to ensure your app will work properly in all browsers without jQuery. The DOM API implementation varies wildly between browsers.

 

All the good plug-ins you need depend on jQuery anyway. I bought into all of these excuses, and more. Some of them were even good excuses at one time.

 

A New Direction, a New Web Developer

Back in the very early days of my web development career, I was transitioning from exclusive server-side work. I was assigned to Jennings, a web-based journalist production tool. I had no professional HTML, CSS, or JavaScript experience. My front-end skills were lacking, to say the least.

 

No one on the team was comfortable with web development. We were all rookies, former back-end developers struggling in vain to make sense of our knowledge in this new context. The deadlines were strict, the goals lofty.

 

It seemed that we all needed some help—perhaps a tool to make our jobs a bit easier. There was no time to learn. We had an application to write!

 

Shortcuts and My Own Stunted Growth

My first exposure to JavaScript and the web was filtered through jQuery. In fact, I didn’t even bother to learn proper JavaScript. I didn’t have a clue what the web API looked like, or how to deal with the DOM directly.

 

jQuery did everything for me. This huge gap in my knowledge caught up with me when I later ended up on a project without my jQuery crutch. I was forced to learn proper web development, and I never looked back.

 

After Jennings, jQuery was a requirement (for me) in all future projects. It was a must because I didn’t know any other way to tame the browser. This didn’t seem unusual at the time. In fact, it wasn’t. jQuery was an expected dependency in most applications and libraries. My blind faith was not an obvious hindrance.

 

Some of the issues of this blind dependency became apparent, to some degree, as I searched for plug-ins to solve common problems in my projects. jQuery is a useful library by itself, but it only addresses core, low-level concerns.

 

If you want to support higher-level features, such as a modal dialog, you need to either write this yourself or find a plug-in that has already solved the problem for you.

 

Naturally, I looked exclusively for jQuery plug-ins to fill the holes in my projects. In fact, I shied away from anything that didn’t depend on it. I didn’t trust any plug-in that didn’t make use of this wonderful magic box.

 

jQuery solved all my problems and made cross-browser development easy for me. Why should I trust the work of a developer who hadn’t achieved this same level of enlightenment?

 

After a short while, it became apparent that the quality of many of these jQuery plug-ins was surprisingly low. The reality is, the low barrier to entry of jQuery is a double-edged sword. Sometimes it’s easy to quickly write something useful. But it's even easier to write unmaintainable bug-prone spaghetti code, quickly!

 

I found that a lot of these plug-ins were very poorly written. My novice knowledge of web development made it tough to sort through and work around the issues I encountered with these jQuery plug-in libraries. Frustration set in, and cracks in my foundation as a developer began to appear.

 

But bugs and inefficiencies in poorly written libraries only exposed the tip of the iceberg. Leaky abstractions in these plug-ins and even jQuery core were rampant and nearly impossible for me to make sense of.

 

Why can’t I trigger a custom event handler created outside of jQuery with jQuery? jQuery supports custom events—why doesn’t this work?

 

This was a specific issue I ran into when working on a project that relied both on jQuery and Prototype, an alternate JavaScript web framework with similar goals. I naively thought I could easily trigger custom event handlers bound with Prototype using jQuery—no such luck.

 

Take file uploading as another example. One would think that uploading files using jQuery is as simple as including the file as the data in the request. Not so. If you do that, jQuery will attempt to URL-encode the file.

 

After a frustrating amount of reading and experimentation, I learned that two obscure properties must be set to false to ensure that jQuery does not attempt to modify the file before the request is sent.

 

Yet another issue developers run into when blindly relying on this library: sending cross-domain requests in older browsers is unintuitive with jQuery. This is a surprising realization to make when working with a library that is supposed to iron out web API differences and allow older browsers to be managed with ease.

 

jQuery’s attribute handling utility function changed in drastic ways over the course of the library’s life. Let’s consider a common task as an example: determining the state of a checkbox.

 

In older versions of jQuery, the correct approach via jQuery was to make use of the attr() method. If the checkbox is checked, a simple invocation of $(checkboxEl).attr('checked') would return true. Otherwise, it would return false. For a seasoned JavaScript developer, this is an odd behavior in itself.

 

For a narrowly focused jQuery developer, the story of this portion of jQuery’s API gets worse. In later versions of jQuery, the same call would return the value of the checkbox element’s checked attribute (which does not naturally change as the checkbox is checked and unchecked).

 

Although this is actually the correct behavior, as it properly mirrors the element’s actual attribute, it was confusing for me after the breaking change. I didn’t have a proper grasp of HTML due to my over-reliance on jQuery.

 

I didn’t understand why I later had to rely on jQuery’s prop() method to obtain the current state of the checkbox, even though the old behavior or the attr() method was technically incorrect.

 

I fell into a trap, and this is a trap that many new, occasional, and hobbyist web developers fall into. Had I taken the time to understand JavaScript and the API provided by the browser first, I would have saved myself a lot of trouble. The proper sequence of events is this:

  • Learn JavaScript.
  • Learn the browser’s API.
  • Learn jQuery (or any other framework/library that you may need across projects).

 

Many start with #3, delaying #1 and #2 to a much later date (or never). If you don’t understand what jQuery is actually doing for you, there will be many frustrating days ahead as the leaky abstractions come out of the woodwork.

 

This is a trap you must avoid if you want to effectively grow as a web developer—a trap that stunted my career as a web developer for longer than I would have liked.

 

A Challenge No jQuery Allowed

A Challenge No jQuery Allowed

In early 2012, I began to replace the Java Applet uploader in Widen Collective, Widen’s flagship digital asset management SaaS offering. Dealing with Java in the browser turned out to be a nightmare, and we were eager to move to a native JavaScript/HTML solution.

 

I first looked into jQuery File Upload (the most popular upload library at the time,  but was put off by a large number of required dependencies needed to get this up and running as well as the lack of cohesive documentation. So, for one of the first times in my web development career, I settled on a non-jQuery solution, and I was a bit lost at first.

 

The library I decided to replace our Java applet uploader with was, at the time, called values/ file- uploader (due to its location on GitHub). It was unique in the respect that it was completely dependency free.

 

I was a bit skeptical at first as I was trained to put a lot of faith in the jQuery ecosystem, but was pleasantly surprised at the ease at which I was able to integrate the plug-in.

 

However, the plug-in had fallen into disrepair. It was no longer actively maintained and needed a few bugs addressed and features tweaked in order to make it production-ready for Widen Collective.

 

Though the work required wasn’t substantial, it took a significant amount of time me to address these issues due to the large gaps in my knowledge of JavaScript, HTML, and CSS. I pushed some of my changes back up to a forked GitHub repository. My code was sloppy and flawed, but it was sufficient.

 

My efforts were apparently noticed by the creator of the library, Andrew Valums, who asked if I was interested in maintaining the library.

 

Even though I had very little practical experience outside of jQuery, I jumped at the opportunity and accepted. I was now the sole maintainer of a large and very popular non-jQuery plug-in, to be renamed Fine Uploader.

 

When I took over maintenance and development of Fine Uploader, a large cross-browser file upload library in mid-2012, my first instinct was to rewrite it all using jQuery, because that would make my life easier (I thought).

 

The existing user community was very much against bringing any 3rd- party dependencies into the library, so I was forced to deal with the native web API and vanilla JavaScript instead.

 

Focus on the Implementation, Not the Magic

Jquery Implementation

The magic of jQuery and its promise of easy web application development is alluring. But we’ve discussed how and why you can become a stronger developer by understanding your environment first.

 

Learn your trade by following the proper route: JavaScript, HTML, CSS, and the web API first. Worry about libraries later.

 

Let me be frank with you and admit that it is truly both interesting and surreal for a former clueless rookie web developer to now be playing the part of the wise “I’ve seen everything” developer.

 

But I can say, with a high degree of confidence, that you are in a much better position to decide when you need to use jQuery, and when you don’t, if you are more familiar with the fundamentals of web development.

 

Knowledge and experience give you the freedom to make this choice and justify it with facts. You aren’t permanently attached to any library. You have options.

 

Don’t hide behind your tools—own your code. Become a web developer and a teacher, not a jQuery developer and a library user. There is something liberating about saying “I don’t need jQuery anymore.

 

I can do it myself!” and actually mean it. Don’t get into the habit of taking shortcuts. Start out on a trajectory that you can be proud of as a professional.

 

Don’t put off learning the fundamentals until later, because later never happens. Avoid helplessness when your library of choice fails to shield you from the browser.

 

You cannot realistically expect to hide behind a layer of abstractions for your entire career. The fundamentals are building blocks that will propel you further and empower you to master your trade.

 

You Don't Need jQuery (Anymore)

The primary goal of this blog is to explain why a web developer like yourself should or should not use jQuery when developing a library or application. For example, the file size is one common consideration when choosing browser-based dependencies.

 

I cover the importance of this attribute and determine how it factors into your decision to utilize this library. Including exploration of the file size argument, the usefulness of jQuery will be further analyzed.

 

As part of this particular exploration effort, I will contrast the common reasons why developers choose to use jQuery against the problems that the same developers may run into as a result of this choice.

 

I may even briefly investigate and discuss other libraries that may be used in place of jQuery or even propel it into obsolescence, though this will mostly be limited.

 

The focus of third-party code will be centered around adopting smaller and more focused libraries and shims. The future of the native functionality provided by the browser will also be a point of discussion.

 

Upon completion of this blog, you will in a better position to decide whether jQuery should be part of your current or future projects. Your understanding of the importance of such a library will become clear, and many common meritless excuses will be refuted.

 

You will also be empowered with choices. If you do desire a bit of help on a complex project with ambitious goals, jQuery is never your only option.

 

The future of web development, in terms of the evolving native browser tools, will give you confidence if you do decide to leave jQuery behind. The term anymore in the title of this blog has a double meaning.

 

You don’t need jQuery anymore because the web API and JavaScript are sufficiently evolved such that a wrapper library can be omitted in favor of a closer-to-the-metal approach.

 

You don’t need jQuery anymore because your confidence and knowledge as a web developer will also be sufficiently evolved after reading this blog.

 

Need vs. Want

 jQuery

The struggle between need and want is not specific to software development, but it is a particularly prudent conflict to be aware of when planning a web project.

 

Often when we make decisions regarding dependencies, IDEs, and build tools, our choices are more focused on want than a need. Why do some of us choose WebStorm over vim?

 

Certainly, vim provides us with everything we need to develop a full-stack web application, but we may feel more comfortable with WebStorm due to its flashy UI and exceptional usability and intuitiveness.

 

Why not use Make or shell scripts instead of grunt or gulp? We can define tasks to automate aspects of our project’s build system with a Makefile, but grunt provides a more intuitive set of conventions and integrations that JavaScript developers can easily grasp.

 

Both Sides of the Acceptable Use Argument

The goal of this blog is not to declare jQuery to be “persona non grata.” My intention is not to pick on jQuery, but rather to teach about the browser’s native tools and provide you with the confidence to develop your web projects without feeling helplessly dependent on a library.

 

So, let’s discuss frankly when it is acceptable to put the “magic” of jQuery to use in your project and when it is not.

 

Let’s put necessity aside for a bit and focus more on want. With a proper understanding of the instances in which jQuery is an acceptable choice, you will be able to make the correct decision when planning future projects.

 

When Is It Acceptable to Use It

jQuery as a project dependency.

If you are quite comfortable with front-end web development and are just looking to write more elegant code, admittedly there aren’t many good reasons to avoid jQuery as a project dependency.

 

This doesn’t mean that you absolutely should use it, but feel free to do so if you desire. If you also feel comfortable with jQuery, and you are familiar enough with how jQuery works its magic, then, by all means, keep using it.

 

There are certain aspects of “ancient” browsers that may make jQuery, or at least certain modules of the library, worthwhile. Let’s define an ancient browser as one that is older than Internet Explorer 9.

 

Anything that isn’t an ancient browser can be considered a modern browser. I talk more about ancient, modern, and evergreen browsers in the next blog.

 

Ancient browsers tend to have substantial API differences compared to modern browsers. Take event handling as an example. In Internet Explorer 8 and older, event handlers must be registered with the attachEvent() method, and event names passed to attachEvent() must be prefixed with “on”.

 

Also, some important properties and methods of the Event object are non-standard. Input element “change” events do not bubble, and event capturing is not supported at all.

 

These browsers also leave a lot to be desired in terms of API and feature support. Ancient browsers lack CSS3 selector support. The useful indexOf method is missing on the Array prototype. Very old browsers cannot natively parse or create JSON and lack a way to easily distinguish an element from an object.

 

These are just a few of the struggles ancient browsers present. In some cases, jQuery was especially important when these browsers were commonly supported. If you are in the unusual and unfortunate position to require support for such an old browser, jQuery may not be a bad library to use.

 

There is usually little benefit to extracting jQuery from a large legacy project. In cases where an enterprise web application has shed support for ancient browsers, it may be tempting to try to eradicate unnecessary browser-based dependencies.

 

I have found myself in this very situation more than once. From my experience, large multi-purpose all-encompassing libraries such as this tend to become firmly entrenched in a complex project over time.

 

Perhaps a planned major rewrite of the application is a prudent excuse to remove these types of monolithic dependencies, but anything short of this would likely render such an undertaking fruitless.

 

Unless your suite of front-end automated tests is exceptionally comprehensive, you may find that the risk of removal far outweighs any perceived drawbacks to leaving the library in place.

 

When writing unit tests for your front-end code—and you should always write tests—jQuery is an acceptable dependency. In a testing environment, performance and page load time are not notable factors, nor is file size. In fact, writing unit tests using some higher-level language or abstraction has some observable benefits.

 

A common thought is that unit tests should not only serve to test your code but to document it in terms of expected behaviors. An elegant and terse testing framework certainly makes tests more maintainable and, most importantly, readable.

 

Finally, there is no shame in using a little help on a one-off project. Someone without any career ambitions in the web development space working on a small and straightforward project is probably not giving up anything by leaning on jQuery to expedite the process.

 

If you’re simply not a developer and need to get, for example, a WordPress site up and running, jQuery can be a notable asset.

 

This is a situation where the car and driver analogy holds up. In this case, you are a driver, not a mechanic. The browser is a mere convenience and not a central tool of your trade.

 

When Should You Refrain from Using It

performance issues with jQuery’s hide()

If your project only supports modern browsers, especially evergreen browsers, you may find it especially easy to do without the conveniences that a wrapper library provides.

 

As browsers evolve, so does the web API and JavaScript. The higher-level amenities that a library like jQuery provides are quickly being represented natively in modern browsers as the associated specifications evolve.

 

For example, the ability to add, remove, and check for CSS classes was previously a chore without jQuery’s addClass(), removeClass(), and hasClass() methods.

 

But the web specification caught up and now provides a native classList property on every element with add(), remove(), and contains() methods. This is perhaps an example of jQuery’s powerful influence on the web specification.

 

As the browser’s native API continues to push forward, the necessity of jQuery also decreases. Instead of pulling a redundant dependency into new projects, consider relying on the power of the browser instead.

 

When writing a generic reusable library, especially open source, your instinct should be to keep third-party dependencies to a bare minimum. Your library’s dependencies become your user’s dependencies as well.

 

Due to the current ubiquitousness of jQuery, you might think it safe to use in any exported code. Odds are, projects making use of your library are already using jQuery. But what if they aren’t? Will a discerning web developer pull in a large transitive client-side dependency solely for the use of your library?

 

Perhaps not. This scenario will become much more common as the web evolves and developers elect to shed these types of abstractions. Personally, I would skip over a library with otherwise unnecessary dependencies, and I don’t believe that this position is unique, based on input I have received from users of a large JavaScript library I maintain.

 

As a library developer, your job is to solve complex problems and package them up in a box that is proportional to the size and scope of the problem you are solving.

 

Performance of your application is perhaps another reason to reject some dependencies, especially one as complex as jQuery. As the user of such a mature and popular library, you would naturally assume that the most basic and common areas of the codebase are all heavily optimized. In this context, efficiency is expected.

 

Sure, perhaps some of the more complex and lesser-used functions have some performance implications. But all of the basic convenience methods should be quite performant. Unfortunately, in the case of jQuery, this is not always true.

 

Take the hide() method as an example of the potential performance issues that lay beneath the surface. This seems like a simple operation to implement efficiently. In fact, it is relatively simple to do this. One approach involves defining a proprietary CSS class name in the document tied to a style of display: none.

 

Instead of using a CSS class, perhaps a hidden attribute can be tied to this style instead. On hiding (), add the class or attribute to the element. On the show(), remove it. This results in a simple and performant solution to a simple problem. However, jQuery’s solution to a problem that should be simple is quite complex and inefficient.

 

One major performance bottleneck in jQuery’s implementation of the hide() method is due to the use of getComputedStyle(), a web API method that computes the actual set of styles of an element, taking into account CSS files, <style> elements, and inline or JavaScript modifications to the element’s style property.

 

The use of getComputedStyle() is appropriate in some cases, but hiding an element may not be one of them. The use of this method in jQuery’s hide() implementation has serious performance implications.

 

Benchmark testing indicates that this approach is about 90 times slower than simply defining a style via an attribute and setting that attribute on the element to be hidden. This specific performance issue is likely to be an unexpected one, even to a seasoned developer. 

 

The performance issues with jQuery’s hide() method are so substantial, that the implementation was significantly simplified in version 3.0, which removed this particular performance bottleneck.

 

Still, for any developers using jQuery 2.x or 1.x, the problem remains, and the changes to hide() in 3.0 are so drastic that it may be a bit of work for some to migrate to jQuery 3.0 in a large project that has depended heavily on this method.

 

This is a good example of how blind faith in an all-encompassing library can lead you down the wrong path. If you want to maintain ultimate control over the performance of your code, you should think twice before pulling in this type of library, lest you unexpectedly run across other efficiency bottlenecks.

 

Of course some performance issues may be more related to your use of the library than anything else. But still, it is surprisingly simple to unknowingly write inefficient code with jQuery.

 

Consider the following code listing that loops over a set of elements that contain a CSS class of “red” and removes any that includes an attribute of “foo” with a value of “bar”:

. Removing Elements with jQuery: Naïve Approach

$('.red').each(function() {

if($(this).attr('foo') === 'bar') {

$(this).remove();

}

});

 

The preceding code certainly works, but it has some notable performance issues. A novice developer and jQuery user without a good understanding of CSS selectors and the implications of looping over a large set of elements may not know that there is a much simpler and more efficient way to solve the same problem.

 

Here is a much more performant and elegant solution to the same problem:

$('.red[foo="bar"]').remove();

 

The execution time between the two approaches is not noticeably different given a small document. But if the document domains a large number of elements with a CSS class of “red”, say, 200, the consequences of the first approach are notable.

 

The former solution is about six times slower than the one-line solution with a complex CSS selector — Chrome 42 using jQuery 1.11.2.).

 

You can still write highly performant code with jQuery, provided you know which methods in the API to avoid, and when. The same is true of the browser’s API, but libraries often provide a false sense of security. Code that makes use of the web API directly is a bit more explicit and specific in its intentions.

 

jQuery, on the other hand, provides a more high-level and seemingly magical API that obscures many details of the implementation and glosses over potential performance tradeoffs.

 

We often don’t want to look past the abstraction’s conveniences, but you must. If you want to write a solid and highly efficient code, you must not only understand jQuery itself (if you choose to use it) but how jQuery makes use of the web API. Blind faith here can present problems in many forms.

 

Another consideration that may require avoidance of jQuery involves page load time. An over-reliance of jQuery’s ready() method is one example. The ready() method executes a passed function only after all elements in the document have been loaded on the page.

 

This doesn’t really have a notable effect on actual page load time, but it does affect perceived page load time. Commonly, any code to be executed by jQuery’s ready() method is imported at the top of the document (usually in the <head> element).

 

And if all scripts are loaded at the top of the document, this may result in a noticeable delay in page rendering, since the scripts must be loaded and executed before the elements. The recommended approach, wherever possible, is to load all scripts at the bottom of the document instead.

 

This results in a much faster-perceived page load time as the document elements load before anything else. If you follow this convention, using $.ready() is no longer necessary. The use of jQuery’s ready() method is widespread and even used regularly in the example code on jQuery’s learning site.

 

This is another instance where you would be better off understanding all the possible options (such as loading your scripts at the bottom of the page) instead of blindly relying on the convenience methods that jQuery provides, such as ready().

 

Somewhat connected to page load time is file size. I’m referring to the size, in bytes, of any resources that your page must load in order to fully render on page load. One common argument against depending on libraries such as jQuery revolves around a file size.

 

The reality is that bandwidth is limited, and all client-side dependencies downloaded by the browser on page load consume some of this bandwidth.

 

If your users all have a 60 Mbps downstream pipe available, the scripts pulled down by your application will probably not have any noticeable effect on page load times. But what if your users are not so lucky?

 

What if they only have access to DSL, which maxes out at 6 Mbps downstream? What if you are targeting mobile devices? In that case, downstream bandwidth may not exceed 4 Mbps. In developing nations, your users may only have access to EDGE, which peaks at about 400 Kbps. Are you considering all of your users?

 

The size of jQuery may or may not be significant to you and your users. If you decide to load jQuery from a CDN, there is a greater chance that the round trip will be avoided altogether.

 

Because this library is so popular, there is a chance that many of your users have already cached jQuery in their browser from another application. But this is certainly not guaranteed.

 

The sheer number of versions of jQuery in active use makes it less likely that the specific version of your project depends on will be cached by the majority of your users.

 

There are also potential disadvantages to depending on a third-party server for your production runtime dependencies. If this server experiences technical issues, your application is likely to be crippled as a result, even if all servers under your control are functioning as expected.

 

If you host jQuery yourself or via a private CDN, you have much more control over how it is served, and where it is served from (taking the user’s location into account).

 

Or perhaps you are worried about the overhead of individual HTTP requests and elect to serve jQuery combined with all other page resources as the response to a single request.

 

Combined with GZIP compression, this is not a bad strategy. But when your user base relies on exceptionally low-bandwidth connections, keeping your resource list small is still of utmost importance. If the first-page load takes a noticeable amount of time, you may just lose a potential customer.

 

Should You Use Other Libraries Instead

dependence on jQuery

One goal of this blog is to push you to remove your dependence on jQuery. But the only alternative I have offered to a monolithic wrapper is a direct attachment to the browser’s native API.

 

This is certainly an admirable goal, and in a sense, the browser is all we need to develop all of our front-end projects. But realistically, we may need a bit more help to reduce the inevitable hand-wringing that occurs when putting together something overly complex.

 

The assumption is that we are targeting modern browsers, and this is reasonable given the current state of the web. But even “modern” browsers with an evolved API may have inconsistent support for some of the powerful features that we need for our projects.

 

If only there was some way to make consistent use of modern web and JavaScript features across all modern browsers, without wrapping the entire stack. 

 

Small Shims Over Large Wrappers

Regressive libraries

There is a concept in web development that describes a very specific type of library, a regressive library. This is a new term, one you have probably never heard of before because I just coined it myself.

 

Regressive libraries are a reasonable alternative to large wrapper libraries. While they are usually small (though not always), their true appeal is evident in the name—they are regressive.

 

Though most libraries evolve in size and feature sets over time, regressive libraries devolve. The ultimate goal of a regressive library is to disappear, to be replaced entirely by the browser’s native API.

 

Regressive libraries are more popularly known as shims or polyfills. They don’t provide any new APIs. Their job is to temporarily fill in missing implementations for standardized APIs in non-compliant browsers.

 

These libraries keep us focused on native tools. There are no abstractions to cloud our understanding and hide the true nature of the web.

 

Polyfill code is usually constructed such that it is only ever used if the browser does not contain a matching native implementation. If the browser does contain appropriate native code, the library delegates directly to the browser instead.

 

One example of a commonly used polyfill is the json2 library by Douglas Crockford. It contributes an implementation for the JSON object in browsers that do not contain their own native implementation. As expected, the API of json2.js is a one-to-one match to the JSON API standardized in the ECMAScript

 

jQuery isn’t part of the future of web development, but neither is any of the other large and currently popular libraries or JavaScript frameworks. Libraries come and go; the browser’s API and JavaScript will outlive them all. The future of the web, and of your career as a web developer, is codified in the web and ECMAScript specifications.

 

These specifications are rapidly evolving—they are quickly catching up to the libraries. Native solutions to common problems usually result in improved performance and increased convenience.

 

There is nothing necessarily wrong with using wrapper libraries like jQuery. However, it is imperative that you have a proper understanding not only of the code that jQuery itself depends on, but also of the reasons why you have chosen to use it.

 

You do not really need jQuery, but if you still want to use it, be sure to take note of the situations where its use is acceptable and of those where you may want to consider forgoing this particular abstraction.

 

Understanding the Web API and “Vanilla” JavaScript

 Web API and Vanilla JavaScript

Before we further explore the mysteries of the browser, JavaScript, and jQuery, there are a number of important concepts and terms to cover. If your plan is to better understand all the different native tools available to you in the browser, it is imperative that you are aware of the history of these tools and how they are interrelated.

 

Browsers can be lumped into a few different categories. You’ll hear about many terms used to describe these categories, such as modern and evergreen browsers, both in this blog and elsewhere—something that will be discussed in more detail in this very blog.

 

A discerning look at the necessity of these categorizations will reveal why some of the groupings are moving targets and potentially of dubious importance. And in addition to browser-based JavaScript, you’ll even learn about how the language can be used outside of browsers, such as on the server, thanks to Node.js.

 

Both the web API and the language of JavaScript are the main topics of discussion in this blog. Before covering the intricacies of the syntax and use of these two items, you will need to be clear about their role and importance. I go into great detail defining the web API and JavaScript and how these two essential concepts are related.

 

Another important goal of this blog is to illustrate how these two technologies have been influenced by standardization. The organizations that curate these standards will be detailed. After completing this blog, you will be quite comfortable with the various specifications that make up the native browser stack.

 

Modern Browsers

Modern Browsers

The modern adjective can be used to describe all browsers newer than those thought of as ancient. At the time of writing, modern browsers are all those newer than and including Internet Explorer 9.

This list also includes Chrome, Firefox, and Safari version 6+. But this modern categorization does share a common trait with the ancient one.

 

The trailing edge of this category is a moving target. What is modern now may be ancient in a few years. Similar to ancient, modern is simply to be used as context when reading this blog. I will often use these terms when describing the browser support for a fragment of code.

 

Modern browsers are, compared to their ancient counterparts, much easier to work with due to their relatively evolved developer tools, web API and JavaScript support, and stability. They account for a set of browsers that can be eloquently addressed without the help of a wrapper library like jQuery.

 

The urge to programmatically identify this class of browser is great. If we can easily determine if we are dealing with Internet Explorer 9 versus 8, or Safari 8 versus 5, then perhaps we can then define two discrete code paths—one for ancient browsers, and another for modern ones. But you should resist this urge.

 

This blanket classification of browsers, based mainly on age, is frivolous. Even worse is identifying browsers in this category and making all your code path decisions based on the browser’s user agent identification string.

 

The correct approach is to test a browser’s API implementation for the presence of, or lack of, a specific feature and then take the appropriate code path for that specific feature.

 

I want to make this clear to be sure that the classifications I have proposed thus far are seen in the proper context and not elevated to a higher level of importance than they deserve.

 

Note A user agent string is a series of characters that identifies a particular type and version of web browser. You can obtain the browser’s UA string via JavaScript by checking the userAgent property of the navigator object.

 

Evergreen Browsers

Evergreen Browsers

There is a third class of browser, one that is ageless and ever evolving. Evergreen browsers are the future of the web. Browsers that fit into this category update themselves without any required user intervention.

 

Although they are versioned, most who use an evergreen browser are likely unaware of their browser’s current version number (with the exception of Internet Explorer 10+ and possibly Safari). Updates are completely transparent, even major version upgrades.

 

This allows the browser to seamlessly evolve its web API and JavaScript support. There is generally no option for the user to (easily) remain on an older version. This allows these browsers to more quickly realize new web specifications, and ensure the entire user base is current. The whole ecosystem wins.

 

Currently, Chrome, Firefox, Safari, Opera, Internet Explorer 10+, and Microsoft Edge are considered to be evergreen browsers. This concept is quite popular and accounts for the majority of browsers available today.

 

The model of tying a browser version to a specific set of operating system versions or “service packs” mostly died with Internet Explorer 9 and Windows Vista.

 

Microsoft’s newest redesigned browser, known as Microsoft Edge, is more like the other traditional evergreen browsers in the sense that the version number will be less prominent compared to earlier Microsoft-created offerings.

 

As evergreen browsers take over the web, we can expect to take advantage of the rapidly evolving specifications, security improvements, and bug fixes faster than ever before. In this world, the need for a library to fill in the browser’s gaps becomes much less important.

 

Mobile Browsers

Mobile Browsers

Desktop browsers still account for the majority of web traffic, at least in the United States. However, current measurements show that mobile browser use is rising while desktop traffic is falling. As of June 2016, mobile/tablet devices account for about 42% of web traffic,2 with the remainder mostly attributable to desktop browsers.

 

The steady rise in mobile device use, along with a consistent (and important) mantra of “mobile first”,3 reveal that mobile browsers are just as big a part of the future of the web as evergreen browsers. The mobile web is still arguably in its infancy, but it cannot and should not be ignored.

 

In some respects, many mobile browsers are very much evergreen browsers as well, due to the fact that a portion of them are automatically updated without user intervention.

 

Just as on the desktop, this behavior allows mobile browsing to evolve rapidly and ensures that users are always equipped with the most up-to-date version of their browser of choice.

 

But the benefits of an automatically updating browser have historically been tied to the capabilities of the physical device.

 

For example, old phones running Android 2.x are likely not able to handle a 4.x version, cutting them off from the latest versions of mobile Chrome. The same problem exists on other mobile platforms, such as on older Apple devices stuck on outdated builds of iOS.

 

The mobile landscape is largely dominated by Apple’s iPhone and iPad running iOS and a multitude of other devices running Google’s Android operating system. Though Microsoft is beginning to make a small impression with their Windows Phone operating system.

 

Research in Motion’s Blackberry OS is, for the purposes of this blog (and most other contexts), irrelevant due to its small and declining share of mobile web traffic.

 

Regardless of the mobile device, keep in mind that the code and techniques used to replace jQuery in this blog will apply equally to all modern/evergreen browsers, so the distinction between mobile and desktop is not particularly important in this context, other than for performance considerations.

 

Even with the rising ubiquitousness of the mobile web, the current situation is not all roses and sunshine. Mobile browsers present unique challenges. Profile and battery considerations make performance consequences of our code more noticeable, compared to desktop systems.

 

Mobile browsers, in particular, are a bit less mature than their larger form-factor counterparts. Along with this immaturity comes more inconsistency in specification support between the various browsers.

 

This is often more noticeable when comparing a mobile browser to its desktop counterpart. Chrome and Safari are two examples of browsers that have a presence both on mobile and desktop devices. While these browsers may share the same name across multiple platforms, their goals vary, leading to differing experiences.

 

In some cases, due to very mobile-unique concerns, such as data use, common portions of web specifications behave differently. Take the autoplay Boolean attribute on the HTML5 <video> element as an example, which will ensure the associated video begins playing immediately after loading. Desktop browsers all support this standard feature, but support on the mobile side is a bit different.

 

Safari running on iOS does not observe this attribute to ensure that auto-playing videos do not adversely affect a user’s limited (and relatively expensive) mobile data consumption.

 

There are other similar examples where the unique environment of a mobile browser may result in unexpected implementation gaps. This reality must be considered when writing “mobile first” libraries and applications.

 

 

What Is This Web API and Why Is It Important

 web API JavaScript methods

Simply put, the web API refers to all the JavaScript methods and objects that specifically allow developers to programmatically address and manipulate the browser.

 

This generalized browser API is made up of two distinct parts: one is the Document Object Model (DOM) API, which is a set of methods and properties attached to HTML document nodes, and the second is a collection of other methods and functions available only in the browser environment but not directly related to HTML. If these terse definitions are still a bit murky, no need to worry. 

 

The web API provides everything necessary to create an exceptionally customized and dynamic experience for end users and even other developers. It is constantly and rapidly evolving, such that the web is destined to ultimately replace installed applications.

 

As a professional developer, your understanding of the web API (or lack thereof) will have a substantial effect on your ability to efficiently design and develop rich complex web applications and libraries. 

 

The DOM API

The DOM API

The DOM is a set of methods and objects used to represent an HTML document. These representations are often (but not exclusively) expressed using the most common language of the web: JavaScript. The DOM provides JavaScript objects that mirror elements in a document.

 

It allows elements to be created, located, manipulated, and described. This language binding exposes a host of potential control points among all HTML elements.

 

For example, the DOM API defines a className property on the DOM’s Element interface. This specific property allows for programmatic reading and changing of an element’s CSS class attribute.

 

All other HMTL elements, such as anchors (HTMLAnchorElement), <div> elements (HTMLDivElement), and <span> elements (HTMLSpanElement), inherit from the Element interface and therefore also include the className property in their JavaScript object representations.

 

The element hierarchy exposed in the previous className example is an important one to understand. Common properties and methods available on specific elements are often inherited from a more common element type. The EventTarget type is at the top of the chain, with all other representations of HTML nodes inheriting from this.

 

The EventTarget type defines methods to register event handlers, which all other HTML items inherit. A Node is a sub-type of EventTarget that all other elements inherit from as well.

 

This Node interface provides methods to clone HTML items and locate sibling nodes, among other behaviors. Sub-types of Node include Element and CharacterData.

 

Element objects are, as you might expect, all nodes that can be expressed with standardized HTML tags, such as <div> and <span>. CharacterData items are either text or comments in a document.

 

In addition to per-element control, the document as a whole may also be manipulated using JavaScript. In fact, there is a particular representation of a document, aptly named the Document interface.

 

A Document object inherits from Node (which, if you remember, inherits from the base type—EventTarget). Documents contain properties that, for example, allow all style sheets associated with the markup to be examined.

 

A number of important methods are available as well, such as one that facilitates the creation of new HTML elements. Note that nothing inherits from Document. All properties and methods on the browser’s document object can also be considered part of the DOM specification, for the purposes of discussion in this blog.

 

The DOM HTML specification summary sounds similar to DOM Core but is actually a bit different. It claims that the spec is “a platform- and language-neutral interface that allows programs and scripts to dynamically access and update the content and structure of HTML 4.01 and XHTML 1.0 documents” (emphasis added by me).

 

In other words, the DOM Core specification defines, as you might expect, core functionality that is common to all documents, and the DOM HTML specification extends this core specification a bit and provides a more HTML-specific API. The DOM HTML spec defines common properties of elements, such as id, className, and title. 

 

There are other related standards, such as the Selectors API12 which covers, as you might expect, selecting elements.

For example, the querySelector and querySelectorAll methods are defined on both the Document and the Element interfaces to allow selection of elements in a document using CSS selector strings defined in the Selectors specification.

 

Currently, at Level 4.13 Another related specification is the UI Events specification, which defines native DOM events such as mouse and keyboard events. The DOM4 specification attempts to aggregate all of these standards and more.

 

Then there is the most widely known standard, HTML5, which became a recommendation in late 2014. It is one of the latest DOM specifications and carries forward the goals of DOM4 along with a host of other non-DOM-related specifications (which I touch on in the next section).

 

In the context of the DOM, HTML5 defines new elements (such as <section>, <footer>, and <header>), new attributes (such as placeholder and required), and new element methods and properties (such as naturalWidth and naturalHeight properties of image elements). This is, of course, a very small list of changes.

 

The W3C maintains a document that describes, in quite a bit of detail, the changes brought on by HTML5. Currently, the latest in-progress specification is HTML 5.2, also curated by the World Wide Web Consortium. HTML 5.1 and 5.2 bring some even newer elements to the DOM.

 

The most notable of these new elements is <picture>, which allows multiple image sources to be specified alongside cues to the browser that indicates which image to load. Picture sources can be tied to browser window size or pixel density, for example.

 

In short, the DOM APIs provide a way to read, update, traverse, and create document elements using JavaScript. The elements themselves and their properties are also defined by this family of specifications.

 

The real power in the web is, in part, defined by the DOM APIs. Without it, dynamic web applications would simply not exist in their current form. The only option would be, perhaps, embedded Flash or Java applets—two technologies that are quickly becoming obsolete due to the power of the modern DOM API.

 

And let’s be clear about another thing: jQuery is built on top of the DOM API. Without the DOM API, jQuery would not exist either. jQuery is mostly a wrapper around the DOM API, providing a level of abstraction. A large portion of Beyond jQuery is dedicated to using the DOM APIs with and without the aid of jQuery.

 

Everything Else (non-DOM)

In addition to the DOM API(s), there is another set of APIs specific to the browser that makes up all properties attached to the browser’s window object. A browser “window” contains an HTML document and the document object (which is defined by the DOM API).

 

This window can be programmatically accessed through the JavaScript window object—a global variable.

 

Although the DOM API defines everything attached to the document object, everything else attached to the window object is defined by a large number of other specifications.

 

For example, the File API, which defines a set of methods and properties used to read, write, and identify files in the browser, is represented by two interfaces: Blob and File. Both interface definitions are available on the window object.

 

Another well-known API specification with bindings to the Window interface is XMLHttpRequest, which defines a set of methods and properties used to communicate with a server asynchronously over HTTP. And in addition to new DOM API features, the HTML5 standard defines a large swath of the properties attached to the window.

 

One example is the History interface, which provides programmatic access to the browser’s history. This is exposed as a history object on the window. Yet another example is the Storage interface, which includes representations on the window as sessionStorage and localStorage for managing temporary storage of small amounts of data in the browser.

 

 

JavaScript: A Less Elegant Version of jQuery

Less Elegant Version of jQuery

A common reason to pull in jQuery is to make up for perceived shortcomings in the underlying language itself—JavaScript. This is one of the most frivolous excuses. It’s a bit much to pull in a third-party dependency like jQuery simply for a marginally better way to loop over object properties and array elements.

 

In fact, this is completely unnecessary with the existence of forEach and Object.keys(), both of which are available in modern browsers. Or perhaps you think $.inArray() is an important utility function to have at your disposal.

 

The truth is, since Internet Explorer 9—where Array.prototype.indexOf was made available as part of the language—the most elegant solution is to make use of “vanilla” JavaScript instead. 

 

Among front-end developers, especially those with limited knowledge of web development, there is often thought to be two possible options in terms of “languages” to utilize when coding your client-side application: jQuery or JavaScript. The flaw in this set of options is obvious to seasoned web developers. Only one of these two “languages” is actually a language.

 

JavaScript is, in fact, a standardized language, whereas jQuery simply provides a collection of utility methods that aim to make solving common problems with JavaScript easier and more elegant across a wide range of browsers. jQuery is nothing more than a collection of web API wrapper methods.

 

JavaScript is both ubiquitous and unavoidable when developing web applications, and with the advent of Node.js, JavaScript is now a viable option on the server as well. In the following sections, I explain the significance of JavaScript, as a language, in the context of web development.

 

Beyond jQuery does not have an explicit goal to dive deep into language syntax and core concepts such as inheritance and scope, though these forms of language details may appear at times throughout the blog if there is a clear tie-in to the layer of abstraction offered by jQuery.

 

Instead, you will gain an understanding of JavaScript’s connection to the web API. The history and standardization of the language will be explored as well, similar to our previous discussion of the web API.

 

Note Actually, JavaScript is technically avoidable, especially since the advent of web assembly, but that standard is in its infancy. If you are writing in a non-traditional front-end language that compiles to web assembly, assuming web assembly is solid (which is currently not the case), then you are probably safe from JavaScript. But short of that, it is still quite important and unavoidable.

 

The Language vs. the Web API

JavaScript is an integral component of the web API. Take the DOM, for example. While the browser DOM is usually implemented in C or C++ and packaged as a layout engine (such as Safari’s WebKit and Chrome’s Blink), the DOM is most commonly manipulated using JavaScript. For example, consider working with DOM element attributes for a moment.

 

To do this, there are three attribute-related methods described in DOM Level 1: getAttribute, setAttribute, and removeAttribute. Additionally, DOM Level 2 provides has to Attribute).

 

All four of these methods are defined in the Element interface, which has a corresponding (and commonly known) implementation in JavaScript. Given any HTML element, you can read and manipulate its attributes in JavaScript just as they are defined in these specifications. 

 

In addition to the DOM, JavaScript is also used when interacting with portions of the web API that are not tied to the DOM, such as the Web Messaging API, which is part of the W3C’s HTML5 specification. The Web Messaging API provides a way for different browsing contexts to communicate with each other via message passing.

 

This opens up an easy way for two iframes on different domains to communicate, or even communication between the browser’s main UI thread and a Web Worker threads. This specification defines a MessageEvent interface, which allows a client to listen for passed messages.

 

In JavaScript, this event object is implemented in all modern browsers and allows developers to listen for messages using the addEventListener method available on the window, document, and element objects.

 

These objects get this method from the EventTarget interface, which you may remember from earlier in this blog, is the top-level interface from which many other native browser objects inherit from.

 

Although JavaScript is key to working with native browser-specific APIs, as a language it is not to be confused with the web specifications themselves. JavaScript is used to interface with implementations of these web specifications in the browser, but the language itself has its own specification: ECMAScript, which I will discuss a bit more in the next section.

 

Note that it is not tied to the Web, though it is implemented in all web browsers. The web API, in some ways, builds on the foundation provided by the JavaScript API. Arrays, Objects, Functions, and primitives such as Booleans and strings are all defined in the JavaScript spec and available in the browser (among other environments).

Recommend