Best practice for using DOM Level 0 in modern JavaScript applications

后端 未结 5 1403
一整个雨季
一整个雨季 2021-02-01 04:55

Is there an agreed set of \"best practices\" for use of the DOM Level 0 collections in modern JavaScript applications? (document.forms, document.images

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 05:40

    That's a very interesting question. Here are my two cents.

    First, it might go without saying, but it depends on whose code you're working on. Professional programmers aim to follow company-wide (or, for larger companies, team-wide) best practices, and if DOM Level 0 is discouraged or forbidden by these guidelines, then you should not use it. If it's either allowed or not mentioned at all, then the decision resolves to a personal choice, like for your own code.

    Now, there's no obvious technical drawback that prevents you from using Level 0 if you wish to do so. For instance, I would be surprised if iterating over element.options was any slower than over element.getElementsByTagName("option") or $("option", element). The first syntax is also arguably more readable than the alternatives.

    Browser support is not a problem either. Level 0 is older than dirt and has been supported for more than a decade by every script-aware browser under the sun.

    However, the above is about choice, not efficiency, which is what the second half of your question is concerned with. Indeed, you can iterate over element.options or $("option", element) or $(element).children("option") with more or less the same efficiency, but if you have to do heavy work (for instance, wipe out the existing elements and add new ones), then using element.innerHTML or $(element).html() will definitely be faster.

    That's because the innerHTML Level 0 property and the html() jQuery method (which uses innerHTML internally) both delegate all the markup parsing and DOM manipulation to the browser, which is usually written in a lower-level language and heavily optimized for these tasks. Removing the elements one by one in a Javascript loop will always be slower in comparison, and in this situation, using DOM Level 0 or all the bells and whistles of jQuery makes absolutely no difference.

提交回复
热议问题