Reputation: 1996
Do browser vendors optimize against jQuery?
I know this sounds absurd anti-standard, but I can imagine browser vendor has optimization against jQuery code built into their JS compiler/interpreter.
For example, lets say the JS compiler/interpreter sees, $('.blah > p'), the browser can say, hmm, I see that user is trying to grab an element, instead of letting jQuery do all the browser detection, it could just take the [actual DOM object], and return $([actual DOM object]) right away.
Upvotes: 0
Views: 220
Reputation: 22421
No browser vendor announced such a feature at the moment.
It is possible, however. You can easily store for reference parsed Javascript (IL/bytecode, whatever you use in your engine) for most often used versions of jQuery inside JS engine and when incoming function matches that signature, replace it with native version.
I guess the only thing that you have to take in consideration is how much time you'd spend on implementing it vs. speed gains against modern JIT engines. Because some of them already compile code to some native form, at least partially, it is not quite clear if there will be any substantial gains or not.
Upvotes: 0
Reputation: 141829
No guessing what $
does would break any scripts that use $
for different purposes. Consider a page like this (this is actually a pretty weak example relative to what could be found in the wild, but I think it still demonstrates the difficulty well enough):
<div class="bar">
<div class="foo">
<div class="bar">
How will the browser know to select this div with the selector '.bar .foo .bar', without actually running this script the way it is designed?
</div>
</div>
</div>
<script>
window.onload = function(){
var x = $('.foo');
console.log(x);
console.log(x.selector) // '.bar .foo .bar'
};
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
var $ = function(){
return arguments[0];
};
$ = (function($){
return function(selector){
return jQuery('.bar ' + selector + ' ' + $('.bar'));
}
})($);
</script>
It would be beyond an optimization for the browser to know which div to select in advance. In fact the browser has to run the scripts the way it is designed to in order to select the correct div.
However many browsers to compile Javascript to a slightly lower level language such as Java or C++ code. Then if the browser downloads and caches jQuery once it will be cached it a compiled form on the users computer. This is not a jQuery
specific optimization since it will happen with any cached script, but it is more significant of an optimization for large scripts like jQuery
.
Upvotes: 4