When to use Vanilla JavaScript vs. jQuery?

后端 未结 13 1920
独厮守ぢ
独厮守ぢ 2020-11-22 09:08

I have noticed while monitoring/attempting to answer common jQuery questions, that there are certain practices using javascript, instead of jQuery, that actually enable you

相关标签:
13条回答
  • 2020-11-22 09:37

    When:

    1. you know that there is unflinching cross-browser support for what you are doing, and
    2. it is not significantly more code to type, and
    3. it is not significantly less readable, and
    4. you are reasonably confident that jQuery will not choose different implementations based on the browser to achieve better performance, then:

    use JavaScript. Otherwise use jQuery (if you can).

    Edit: This answer applies both when choosing to use jQuery overall versus leaving it out, as well as choosing whether to to use vanilla JS inside jQuery. Choosing between attr('id') and .id leans in favor of JS, while choosing between removeClass('foo') versus .className = .className.replace( new Regexp("(?:^|\\s+)"+foo+"(?:\\s+|$)",'g'), '' ) leans in favor of jQuery.

    0 讨论(0)
  • 2020-11-22 09:41

    I've found there is certainly overlap between JS and JQ. The code you've shown is a good example of that. Frankly, the best reason to use JQ over JS is simply browser compatibility. I always lean toward JQ, even if I can accomplish something in JS.

    0 讨论(0)
  • 2020-11-22 09:45

    The first answer's live properties list of this as a DOM element is quite complete.

    You may find also interesting to know some others.

    When this is the document :

    • this.forms to get an HTMLCollection of the current document forms,
    • this.anchors to get an HTMLCollection of all the HTMLAnchorElements with name being set,
    • this.links to get an HTMLCollection of all the HTMLAnchorElements with href being set,
    • this.images to get an HTMLCollection of all the HTMLImageElements
    • and the same with the deprecated applets as this.applets

    When you work with document.forms, document.forms[formNameOrId] gets the so named or identified form.

    When this is a form :

    • this[inputNameOrId] to get the so named or identified field

    When this is form field:

    • this.type to get the field type

    When learning jQuery selectors, we often skip learning already existing HTML elements properties, which are so fast to access.

    0 讨论(0)
  • 2020-11-22 09:45

    As usual I'm coming late to this party.

    It wasn't the extra functionality that made me decide to use jQuery, as attractive as that was. After all nothing stops you from writing your own functions.

    It was the fact that there were so many tricks to learn when modifying the DOM to avoid memory leaks (I'm talking about you IE). To have one central resource that managed all those sort of issues for me, written by people who were a whole lot better JS coders than I ever will be, that was being continually reviewed, revised and tested was god send.

    I guess this sort of falls under the cross browser support/abstraction argument.

    And of course jQuery does not preclude the use of straight JS when you needed it. I always felt the two seemed to work seamlessly together.

    Of course if your browser is not supported by jQuery or you are supporting a low end environment (older phone?) then a large .js file might be a problem. Remember when jQuery used to be tiny?

    But normally the performance difference is not an issue of concern. It only has to be fast enough. With Gigahertz of CPU cycles going to waste every second, I'm more concerned with the performance of my coders, the only development resources that doesn't double in power every 18 months.

    That said I'm currently looking into accessibility issues and apparently .innerHTML is a bit of a no no with that. jQuery of course depends on .innerHTML, so now I'm looking for a framework that will depend on the somewhat tedious methods that are allowed. And I can imagine such a framework will run slower than jQuery, but as long as it performs well enough, I'll be happy.

    0 讨论(0)
  • 2020-11-22 09:46
    • this.id (as you know)
    • this.value (on most input types. only issues I know are IE when a <select> doesn't have value properties set on its <option> elements, or radio inputs in Safari.)
    • this.className to get or set an entire "class" property
    • this.selectedIndex against a <select> to get the selected index
    • this.options against a <select> to get a list of <option> elements
    • this.text against an <option> to get its text content
    • this.rows against a <table> to get a collection of <tr> elements
    • this.cells against a <tr> to get its cells (td & th)
    • this.parentNode to get a direct parent
    • this.checked to get the checked state of a checkbox Thanks @Tim Down
    • this.selected to get the selected state of an option Thanks @Tim Down
    • this.disabled to get the disabled state of an input Thanks @Tim Down
    • this.readOnly to get the readOnly state of an input Thanks @Tim Down
    • this.href against an <a> element to get its href
    • this.hostname against an <a> element to get the domain of its href
    • this.pathname against an <a> element to get the path of its href
    • this.search against an <a> element to get the querystring of its href
    • this.src against an element where it is valid to have a src

    ...I think you get the idea.

    There will be times when performance is crucial. Like if you're performing something in a loop many times over, you may want to ditch jQuery.

    In general you can replace:

    $(el).attr('someName');
    

    with:

    Above was poorly worded. getAttribute is not a replacement, but it does retrieve the value of an attribute sent from the server, and its corresponding setAttribute will set it. Necessary in some cases.

    The sentences below sort of covered it. See this answer for a better treatment.

    el.getAttribute('someName');
    

    ...in order to access an attribute directly. Note that attributes are not the same as properties (though they mirror each other sometimes). Of course there's setAttribute too.

    Say you had a situation where received a page where you need to unwrap all tags of a certain type. It is short and easy with jQuery:

    $('span').unwrap();  // unwrap all span elements
    

    But if there are many, you may want to do a little native DOM API:

    var spans = document.getElementsByTagName('span');
    
    while( spans[0] ) {
        var parent = spans[0].parentNode;
        while( spans[0].firstChild ) {
            parent.insertBefore( spans[0].firstChild, spans[0]);
        }
        parent.removeChild( spans[0] );
    }
    

    This code is pretty short, it performs better than the jQuery version, and can easily be made into a reusable function in your personal library.

    It may seem like I have an infinite loop with the outer while because of while(spans[0]), but because we're dealing with a "live list" it gets updated when we do the parent.removeChild(span[0]);. This is a pretty nifty feature that we miss out on when working with an Array (or Array-like object) instead.

    0 讨论(0)
  • 2020-11-22 09:46

    There's a framework called... oh guess what? Vanilla JS. Hope you get the joke... :D It sacrifices code legibility for performance... Comparing it to jQuery bellow you can see that retrieving a DOM element by ID is almost 35X faster. :)

    So if you want performance you'd better try Vanilla JS and draw your own conclusions. Maybe you won't experience JavaScript hanging the browser's GUI/locking up the UI thread during intensive code like inside a for loop.

    Vanilla JS is a fast, lightweight, cross-platform framework for building incredible, powerful JavaScript applications.

    On their homepage there's some perf comparisons:

    enter image description here

    0 讨论(0)
提交回复
热议问题