I do a little bit of third party javascript work for a company where I am able to enter my javascript snippets into the CMS and have it run in the customer facing sites.
I have the option to switch on JQuery 1.7.1 in the header of the site and I usually choose to do this or not depending on how much more complicated it would make my code if I didn’t.
I have often wondered how much difference it would make if I just turned it on in all cases so even simple things like:
document.getElementById('myElement');
became
$('#myElement');
Where would the ‘breakpoint’ be in deciding it was better / more efficient / easier to switch on JQuery?
Today’s example that made me think of this was as follows (both regular javascript followed by the JQuery equivalent ):
Javascript:
if (document.getElementById('myElement')!== null) {
var oldText = document.getElementById('myElement').innerHTML,
newText = oldText.replace(/one/i,'two');
document.getElementById('myElement').innerHTML = newText;
}
jQuery:
if ($('#myElement').length !== 0) {
var oldText = $('#myElement').html(),
newText = oldText.replace('one','two');
$('#myElement').html(newText);
}
And How much is the negative affect on forcing the clients to download jQuery?
The difference will be minimal, and not worth writing those 10 chars…
jQuery site
And of course
jQueryhas a lot more features than id selectors…A good advise is to cache the queried elements and not query them multiple times, but it’s true both with
jQueryand with vanilla javascript;From:
To:
or jQuery version:
Due to jQuery "chainabilty" – cascading styile, you do that with one "chain":
This
jsperfshows that$('#id')is 3-6 slower thandocument.getElementByIdWhich means you can have "only" 1,000,000 those operations per second… "A disaster"!
"We should forget about small efficiencies, say about 97% of the time: premature
optimization is the root of all evil"
Regarding to the "loading"- downloading time of the jQuery library.