Closed migig closed 9 years ago
While that's true that IDs tend to be a little bit faster than classes, this div is injected into the document only once, at the initialization of the script. Performance improvement of using IDs over classes would be unnoticeable in this case.
No what I meant is not that it's slow during injection, but rather slow when querying.
For such an obvious perf gain, it makes sense to use an ID, especially since it's backwards compatible (won't break anything as the library handles all that stuff internally).
We use the library's main is
function heavily, and in the long run, those full-DOM scans add up.
The alternative is to cache the element in the library, and do the scan only once. (i.e. just save the element as some private variable.)
The way this library works is that it creates jQuery objects from given syntax (visibility divs), and stores these objects internally, as a property (self.breakpoints). These divs are then injected into DOM using internal.applyDetectionDivs (which just uses $.appendTo). From now on jQuery stores a reference to each of these objects.
Therefore, whenever you use any of the methods, they do not query the DOM again, but rather use the reference to a DOM node that has been created upon injection, and return a value from (whether the div is visible or not) of that DOM node.
So what I'm saying is, the 'caching' you mention in the last paragraph is what is happening here. Here's one way of verifying it.
// Create jQuery object
var $detectionDiv = $('<div class="device-xs"></div>');
// Append to DOM
$('body').append($detectionDiv);
// Change div value of jQuery object
$detectionDiv.text('aaaa');
// Even though we only altered $detectionDiv
// value of the div in DOM has also changed
// This step does not happen in the library. It's here for verification
$('.device-xs').text();
@maciej-gurban Great! :beer:
The injected
<div class="responsive-bootstrap-toolkit"></div>
would be found faster if it used anid
rather than aclass
.Unless it's cached, but I couldn't figure out from the code if it does that.