Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

jquery - CSS Optimization: Element ID vs. Class

With MVC and jQuery I am making significantly more use of CSS. A question that came to mind is what is the best approach for using Element IDs vs. Classes. If I use Element IDs the selectors in jQuery are shorter. For example:

#imageTag... $('#imageTag')
#searchTag... $('#searchTag')

As an alternative it could be structured with a parent container element.

#searchTool, #classifyTool .tag

In this case selectors such as

$('#searchTool .tag') or $('#classifyTool .tag')

could be used. This approach can be particularly useful when there are multiple instances of a class throughout the page, e.g., .tag. You just change the parent container object.

This is just a simple theoretical example and is not intended to represent real styles, just portray the concept.

So there are two questions:

  1. Is there any impact on performance of either the page/CSS or jQuery assuming there are a large # of styles on a page?

  2. The second approach seems more flexible and maintainable. Thoughts based upon your experiences.

Is there a better alternative approach?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • IDs are the fastest
  • Tag names are next fastest
  • Class names with no tag name are the slowest

As for which one to use, use whichever is most appropriate. If you have a search box on your page then using an ID for that would be most appropriate because there's only one search box. Table rows on the other hand will probably be identified by class because there is (or can be) more than one.

Try not to use selectors (in CSS or jQuery) like ".class". You're forcing jQuery or the browser to basically traverse the entire document tree. Most of the time the class will only apply to one kind of tag so specify that (eg "div.class"). That alone can make a huge performance difference (particularly on jQuery with a large document).

The length of the selector should not be a consideration. Performance, readability and maintainability should be.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...