GitHub: Why would we abandon jquery?

Source: Internet
Author: User
Tags local time ruby on rails
Recently, we removed jquery completely from Github.com's front-end code, which marks the end of our gradual process of removing jquery over the years, a milestone event for us. This article will describe how we relied on jQuery over time, and we realized that we didn't need it anymore, but in the end we didn't replace it with another library or framework, but instead used the standard browser API to achieve everything we needed.
Early on, jQuery meant a lot to us.

Github.com started using JQuery 1.2.1 at the end of 2007, the year before Google's release of the Chrome browser. There was no standard way to query DOM elements through CSS selectors, nor was there a standard way of dynamically rendering elements, and Internet Explorer's XMLHttpRequest interface, like many other APIs, had inconsistencies between browsers.

JQuery makes DOM manipulation, creating animations, and "AJAX" requests quite simple, essentially allowing web developers to create a more modern, dynamic Web experience. Most importantly, the code developed with JQuery for one browser also applies to other browsers. In the early stages of GitHub, JQuery enabled small development teams to quickly prototype and develop new features without having to tailor the code specifically for each Web browser.

The extension library built on the simple interface of JQuery also becomes the base building block for the github.com front-end: Pjax (Https://github.com/defunkt/jquery-pjax) and Facebox (https:// Github.com/defunkt/facebox).

We will never forget John Resig and the JQuery contributors who created and maintained such a useful base library.

Later WEB standards

Over the years, GitHub has grown into a company of hundreds of engineers, and has gradually set up a dedicated team responsible for the size and quality of JavaScript code. We have been excluding technical debt, and sometimes technical debt will grow as dependencies increase, and these dependencies will give us some value at the outset, but these values also fall over time.

We can compare jQuery with the rapid evolution of WEB standards supported by modern browsers:
$ (selector) mode can be replaced with queryselectorall ();
You can now use Element.classlist to implement CSS class name switching;
CSS now supports defining visual animations in style sheets rather than in JavaScript;
The $.ajax request can now be executed using Fetch standard;
The AddEventListener () interface is stable enough to be used across platforms;
We can use the lightweight library to encapsulate the event delegation pattern;
With the development of the JavaScript language, some of the syntactic sugars provided by jQuery have become superfluous.
In addition, chained syntax does not satisfy the way we want to write code. For example:

$ ('. Js-widget ')  . addclass (' is-loading ')  . Show ()

This grammar is very simple to write, but according to our standards, it does not convey our intentions well enough. Does the author expect to have one or more js-widget elements on the current page? Also, if we update the page tag and accidentally omit the Js-widget class name, will the browser throw an exception and tell us what the problem is? By default, JQuery skips the entire expression when nothing matches the selector, but for us, this is a bug.

Finally, we started using Flow to annotate types to perform static type checking at build time, and we found that chained syntax is not suitable for static analysis because almost all of the results returned by jQuery methods are the same type. We chose Flow because @flow weak mode allows us to gradually apply the type to the untyped code base.

To summarize, the removal of jQuery means that we can rely more on web standards, making MDN Web documents the de facto default for front-end developers, maintaining more resilient code in the future, and removing 30KB dependencies from our bundles, speeding page loading and The speed at which JavaScript executes.

Progressive decoupling
Although the ultimate goal is set, we also know that it is not feasible to allocate all resources to remove jQuery at once. This hurried approach could lead to regression of the site's functionality. Instead, we have adopted the following strategy:

1. Set the indicator, track the ratio of the entire line of code to the JQuery, and monitor the movement of the indicator over time to ensure that it remains constant or declining rather than rising.
2. We do not encourage the introduction of jQuery in any new code. To facilitate automation, we created Eslint-plugin-jquery (https://github.com/dgraham/eslint-plugin-jquery), if someone tried to use jquery features, such as $.ajax, The CI check will fail.
3. There are a number of violations of eslint rules in the old code, and we annotated them with specific eslint-disable rules in the code comments. Readers who see these codes should know that the code does not conform to our current coding practices.
4. We created a pull request bot, and when someone tries to add a new eslint-disable rule, they leave a comment on the pull request. This allows us to participate in code review as early as possible and propose alternatives.
5. Many of the old code uses the Pjax and Facebox plugins, so we use JS internally to re-implement their logic while keeping their interfaces almost constant. Static type checking helps to improve our confidence in refactoring.
6. Many of the old code interacts with Rails-behavior, and our Ruby on rails adapters are almost "unobtrusive" JS, which attaches an AJAX lifecycle processor to some forms:

Old Method  $ (document). On (' ajaxsuccess ', ' form.js-widget ', function (event, XHR, settings, data) {    //) Insert the response data into the DOM c2/>})

7. We choose to trigger fake ajax* lifecycle events and keep them as asynchronous submissions as before, rather than rewriting all calls immediately, but using fetch internally ().
8. We maintain a version of jquery ourselves, and whenever we find that we no longer need a module of jquery, we remove it from the custom version and release a lighter version. For example, after removing the CSS pseudo-selector for jQuery (e.g., visible or: checkbox), we can remove the Sizzle module and remove the Ajax module when all $.ajax calls are replaced by a fetch ().
There are two reasons to do this: speed up JavaScript execution while ensuring that no new code attempts to use the removed feature.
9. We discard support for older versions of Internet Explorer as soon as possible based on the results of the site's analysis. Whenever an IE version's usage is below a certain threshold, we stop providing JavaScript support to it and focus on supporting a more modern browser. Abandoning support for IE 8 and IE 9 as soon as possible means that there are many native browser features that can be difficult to achieve with polyfill.
10. As part of the new approach to developing github.com front-end capabilities, we focus on using as much regular HTML as possible and incrementally adding JavaScript behavior as incremental enhancements. As a result, Web forms and other UI elements that use JS enhancements can often work correctly on JavaScript-disabled browsers. In some cases, we can completely remove some of the legacy code without using JS to rewrite them.

After years of effort, we gradually reduced our reliance on jQuery until there was no line of code to reference it.

Custom elements

In recent years, a new technology, the custom element-the native component library of the browser, has been hyped up, which means that users don't have to download, parse, and compile extra bytes.

Since 2014, we have created a number of custom elements based on the V0 specification. However, because the standards are still changing, we are not devoting too much effort. Until 2017, when the Web Components V1 specification was released, and Chrome and Safari implemented this specification, we began to adopt custom elements more broadly.

We are also looking for patterns to extract custom elements during the removal of JQuery. For example, we convert the Facebox used to display modal dialogs to the <details-dialog> element (https://github.com/github/details-dialog-element).

Our progressive enhancement concept extends to custom elements as well. This means that we will keep the tag content as much as possible and then tag the added behavior. For example,,<local-time> displays the original timestamp by default, it is upgraded to convert the time to the local time zone, and for <details-dialog>, when it is embedded in the <details> element, it can be used without JavaScript is interactive, it is upgraded to have accessibility enhancements.

The following are examples of implementing <local-time> custom elements:

Local-time displays the time based on the user's current time zone. For example://   <local-time datetime= "2018-09-06t08:22:49z" >sep 6, 2018</local-time>//class Localtimeelement extends HtmlElement {  static get Observedattributes () {    return [' DateTime ']  }  Attributechangedcallback (Attrname, OldValue, newvalue) {    if (attrname = = = ' DateTime ') {      const date = new Date (new Value)      this.textcontent = date.tolocalestring ()    }  }}if (!window.customelements.get (' Local-time ')) {  window. Localtimeelement = localtimeelement  window.customElements.define (' Local-time ', Localtimeelement)}

We are looking forward to the Shadow DOM of the Web component. The power of the Shadow DOM brings a lot of possibilities to the WEB, but it also makes polyfill more difficult. Because using Polyfill can result in a performance penalty, it is not feasible to use them in a production environment.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.