jQuery Performance : attributes

If you use jQuery you have more than likely needed to do something with an elements attribute(s), whether that be get the value/data from it or set the attribute of an input or add a data attribute for future reference.

As you are probably aware there are multiple ways in jQuery to get different attribute values. These methods are:

.attr()

.prop()

.data()

.val()

If you are not sure on what these four methods do here is a quick overview, but I do recommend going to ready the jQuery Documentation.

.attr() – Can be used to either get the value of a specified attribute or set the value.

$(‘input’).attr(‘type’)would get the value of the type attribute to the input.

$(‘input’).attr(‘type’,’text’)would set the type attribute to text for the input element(s)

.prop() – is used in the same way as .attr() you can either get the value or set it. This was introduced in jQuery v1.6

.data() – is used to store or access custom data from an element, so you can used it to fetch an HTML5 data attribute

$(‘input’).data(‘validation’)would fetch the data-validation attribute value

.val() – Used to the current value of the element(s), or to set the value of the element

$(‘input’).val()Would get me the contents of the value attribute

$(‘input’).val(‘Matthew’)Would set the input value to Matthew

Tests

So with these different ways of getting different attributes and setting them, which one(s) should we be using?

I know I’ve been a sucker for using the .attr() method for most things, and the the .val()method when ever I’ve needed to get or set the value. But I am a performance nerd and like to question myself/ or others on the way they are writing code.

I have put together a set of tests to show some different scenarios of using this methods to see what’s the quickest way, and when you should be using a certain method for a certain tasks.

All tests have been done with the latest jQuery.

Getting element attribute: .attr() vs .prop()

We are testing which method is quickest between .attr() and .prop() to get a standard HTML attribute of an input

Tests

HTML – <input type=’text’ name=’name’ value=’Joe Bloggs’ data-validation=’min: 3′ />

attr – $(‘#test’).attr(‘type’);

prop – $(‘#test’).prop(‘type’);

Results

So as you will see from the graph below the results for this test are very close making it a bit of a tie. There was no clear winner for speed, and one method was not always fastest.

getting_attribute_attr_prop

Test on jsperf

Setting an input value: .attr() vs .prop() vs .val()

Test to see which method is the fastest for setting the value of an input, using .attr(), .prop()and .val()

Tests

HTML – <input type=’text’ id=’foo’ />

attr – $(‘#foo’).attr(‘value’, ‘Test’);

prop – $(‘#foo’).prop(‘value’, ‘Test’);

valĀ  – $(‘#foo’).val(‘Test’);

Results

The results for this are interesting as the clear winner is the .prop() method, but there is also a little difference between firefox and the rest of the browsers, while Firefox is much slower for all three tests, but all three test are very close in performance wise.
The winner is .prop() for this test.

setting_input_value

Test on jsperf

Getting data attribute: .attr() vs .data()

Update – prop() is not always the go to method for getting attributues, it can not get data-xdata and a few others, but I’ll write a post about this.

Test to see which method is the quickest to get the value of a data attribute.

Tests

HTML – <input type=’text’ name=’name’ value=’Joe Bloggs’ data-validation=’min: 3′ />

attr – $(‘#test’).attr(‘data-validation’);

data – $(‘#test’).data(‘validation’);

Results

The one thing I found interesting about this test was I thought that the .data() method would come out on top, as the method name suggest’s that we should use this method to get the data, but turns out this is the slowest. You should either use .attr(). The difference is speed is very slight and varies between browsers.

Test on jsperf

Setting a checkbox: .attr() vs .prop()

Test to get the quickest way to set the checked attribute on a checkbox. This was actually my first test which started off this blog post, but I wanted to cover some basics first to make sure I was not barking up the wrong tree.

I ran two test for each method as you can set the checkbox to checked using the HTML way of checked=’checked’ or by passing true. I write my jQuery using checked over the true way as I have seen some browser issues with the true way.
But I wanted to test the true vs checked way to see if there was any major difference in performance.

Tests

HTML – <input type=’checkbox’ id=’foo’ />

attr – $(‘#foo’).attr(‘checked’, true);

prop – $(‘#foo’).prop(‘checked’, true);

attr checked – $(‘#foo’).attr(‘checked’, ‘checked’);

Prop Check – $(‘#foo’).prop(‘checked’, ‘checked’);

Results

The .prop() method wins hands down on this test, and I was amazed at how much by. Over 40% quicker in some cases which is a lot if you are do a lot of form manipulation with jQuery.
Another surprise I got with the results from this test is the difference in speed between the major browsers. I was surprised by the speed difference of Chrome to Safari, and also the speed of Firefox against the others.

jquery_performance_setting_attributes

Test on jsperf

Conclusion

With running these tests, I learnt that not to rely on jQuery methods that you think are doing the job properly for you. The fastest way to manipulate element’s attributes is the .prop()method.

jQuery Performance: for vs $.each

So you are using jQuery, pretty much everyone is using it (no stats to back this up, but it’s used a lot), and it’s full of awesome stuff. With jQuery, like many other languages it’s also possible to write code that can get you the end result in multiple ways. But is it the most efficient way?

You may think that because you are using jQuery you need to use all jQuery’s function’s, this is wrong. jQuery is just a wrapper around JavaScript functions making them easier to understand and use for the average user. While for 9 out of 10 scenario’s it’s great, the average user may be using jQuery to spice up their website a little to give it some wow factor. But should you settle for average? I say no, but depending on how far you wish to go with jQuery/ JavaScript your answer will differ to mine.

Back a year or so ago, I would of been the one who was saying it’s fine just use the jQuery functions they are nice and easy, it can not be that bad. But since working on some big web apps with hundreds of thousands of users actively using the apps on a daily basis and spending a large chuck of their time doing meaningful work in them. I have started taking a really hard look into the way I am writing jQuery and the performance of the jQuery functions I am using.

A while back I was implementing a bit of custom functionality into a web app, where users could filter rows in a table using an input box, sort of like a live search. The more they type the more rows disappeared. Sounds straight forward enough, but the table is up over a hundred rows and has around 5 or 6 columns.
The code was first implemented using the jQuery $.each function to loop over the rows and determine if the value entered in the search box matched something in the row, if it did cool, if not hide the row. Again sounds straight forward. All seemed to work with the code for a little while, but over time, and when more rows where added and the complexity of the search grew the speed dropped very quickly and at some points there was lots of browser lag and sometimes the browser would crash.

So, I went in search of a fix. I rewrote the code a few times to see if I could make it neater and learner, but it all ended up at pointing to the $.each that was in there. So I went digging into the jQuery source to find that the $.each function is a nice wrapper for a native JavaScript loop.

I re-wrote the $.each to use a for loop and the code works perfect. This lead me onto to do some research into it.

So a quick search reveals a jsperf.com test on a for loop vs a jQuery $.each loop. And as you’ll see from the test data the native JavaScript for loop is nearly twice as fast as a jQuery $.each.

While for the most part the developer who is doing stuff for their personal site or a site for the local business down the road, would not hit the issues I was having with my code in this scenario I found it intriguing at how much faster the native for loop was.

Think of it this way, as the native loop is nearly twice as fast that means I could do the same loop nearly twice, by the time jQuery would have done it once, making not only the site faster, but taking strain away from the browser and giving the user a faster and more tolerable user experience.

The more I write with jQuery the more I am looking into the source to see what it is wrapping for me, as you must not forget jQuery is just a nice library for JavaScript, while it does help with a lot of cross platform/browser issues there is also a lot you can learn performance wise by going into the source and actually seeing what it is doing.

Note I am not suggesting that jQuery do not pay attention to performance far from it, John Resig and the jQuery core developers put a lot of effort into jQuery and I don’t mean to take anything away for that.

But sometimes you are simply not able to match the native speed using a wrapper. I working in jQuery on a near daily basis and love what they have done.

Welcome Almanac

The past few days on Twitter I have seen a lot of tweets regarding static site generators, and engines. These are cool as they are quite basic, no need for database integration, meaning you can run on a very simple host.

A lot of what I came across were PHP, Ruby, Node.js or another web based language based and without a great deal of looking around I could not see anything for the ColdFusion market. With me working in ColdFusion on a daily basis I thought I would create something for the ColdFusion market.

So I would like to welcome Almanac a simple blog engine that works with static MarkDown (.md) files and is written in ColdFusion (CFML). I wrote it using the CFML Engine OpenBD.

A reason I decided to write it was I have a love for the Markdown Syntax, and I wanted something to kickstart my blog again, so as the old saying goes, two birds one stone…

Lending a Helping Hand

Many of you probably already know that I am an active twitter user, hell you probably reading this as I tweeted the link to the article. The majority of my traffic comes from twitter. So with that sorted…

Anybody who is a twitter user will realise that, twitter is not just about telling people what you had for lunch or when you woke up, what the weather is like, etc. Well it is for that, but it’s also has great deal more to it, it’s also a great resource for learning, or finding answers to questions quickly, or even provoking a conversation (bit hard I know, you timeline soon fills up).

Over the years I have been using twitter, I have tweeted about pretty much everything, hell I even tweeted I was going have sex in the shower, some people took it out of context, but I was not lying, I just did not explain myself correctly. I actually had a sex in the showeremotibomb it took some explaining, but it was all good fun.

So, what I am I getting at?

Put all the fun aside, twitter has been a huge help for me, not just making new friends online and having fun, but I have also learned a lot from tweeting questions to what I may of thought to be stupid questions. Being a front-end web developer (as you may already know) sometimes I hit problems with things, generally I’ll Google for a bit and see what I get, but I’ll also tweet my issue at the same time in order to get a more mix of answers, 9 times out of 10, somebody will reply with the answer I am after, great, somebody saved my bacon once more, so times I even get a twitter reply before I have had chance to scan the search results in Google.

These passed few months I have not asked that many questions on twitter in the vain of seeking help for a problem, mainly due to not needing to. Not sure why, maybe I am not pushing the boundaries enough, or maybe I am actually getting smarter. I would like to think the latter.

So with that in mind, these passed few months I have been the person on the other end, I have been offering support to people who have asked the questions, by doing this I have made a few extra friends, had some great Skype conversations with people and even been promoted by the person I helped. Each time I offer my help I am expected nothing in return, one of the main reasons I offer my help/knowledge is it will help you and it also helps me.
How is it helping me? You may ask..

Well, I would say about 20% of the help I offer is to questions that I feel I may be able to help with. You may say why offer the help if you are not sure? Well everyone has to learn somehow, so I see it as an opportunity to help someone out as well as help myself learn that bit more. About 90% of these unknowns I actually do know what the user is asking, this actually scares me a little as I am unaware of my own knowledge until it’s questioned, maybe I am becoming more complacent with my skills/ knowledge and am not pushing them enough.

What next?

Well I am going to keep offering my help why I see someone struggling. In the future I am going to document the problems and solutions so others can also learn from them.

Look forward to helping more people with their problems, also I hope people help me why I get stuck! If you are reading this and your not following me on twitter, maybe you should. My twitter username is Follow me on twitter

The mobile experience

Something that has got me thinking the passed few months has been the whole debate with regards to \”the mobile experience\”. It was not until a little while ago that I hit a slight brick wall while discussing it with a designer.

It started with me showing off how I could make a site responsive with only a few lines of code (bear in mind the site had been designed at 960 wide and never had an intentions to be responsive), making the site accessible for everyone on all screen sizes. The main point that I was putting across was that the user(s) who access the site will all have a tailored solution for them, meaning they would all experience the same content, but rather than struggling with viewing or accessing it, it would be displayed on their screen in the most appropriate way.

From my little demonstration it did not prove to be the hit I thought it might be, greeted with a bit of confrontation with how the site was adapting depending on the screen size, I stated that this was just some basic styling to demonstrate how responsive/ fluid site could work, and with some extra time all the break points could be identified and the site could work from a mobile device up to a desktop computer. I also mentioned that if this approach was to be taken then designing for Mobile first then building upon this would have be the better option, but due to the nature of this particular site it was not so crucial.

So with the slight confrontation I decided I would like to know more about this person thoughts on the matter. So, I started to ask questions with regards to what was wrong with this approach. Questions and awsers where fired back and forth, it seemed we where not actually getting anywhere, the designer had his own opinions with regards to the matter and could not see beyond this. The reasoning behind the designer not being able to see past his thoughts was he kept saying all site’s should have a mobile version for people accessing it on an mobile phone, saying that you don’t get the same experience. By a mobile version he was stating a completely different site designed specific for mobile devices.

I could sort of see his thinking here, but only for certain types of site’s, on why he would think this. Yes, some sites could do with a mobile specific site but for the vast majority of site’s that are around and with the amount of different devices, mobile specific is not the best option as these site’s would not have the budget to have specific sites created to target specific devices. But why when you can employ responsive design?

My question in response was; What are people coming to this website for? The content that is on it! So why would a specific mobile site be need when the content that they are wanting is here, and with some simple rules and a slight change of the design the whole site could be accessed through all mediums and all users are able to see what they need. All users would have a tailored experience and design depending on how they are accessing the site.

I know this subject has been discussed a lot from all angles and situations. I would like to know others thoughts on this. I don’t think this is going away anytime soon and people will always have an opinion for and against each aspect but it’s how we tackle the situation at hand.

How I organise my site files and folders

As a web developer I deal with a lot of files. These are all different and are relevant to different parts and stages of the process. From initial stages of the project when doing research, site architecture, designs, up to the completed site, and then the continual backups. If you are in the same position as me you’ll be able to relate with the amount of files one may have to deal with.

As I work primarily with the website files, here I am going outline how I organise my files and folders to deal with the vast amount of files I work with.As you may already have noticed, the image above is a folder structure of a past project. All sites are stored within my Sites folder, which is also the web root to my MAMP install. Within this folder I have all the sites past, present and some upcoming jobs, and also a boilerplate folder.

My sites folder looks something like this:

  • Site A
  • Site B
  • Site C
  • ZZ

Each site has it’s own folder, and the boilerplate folder is ZZ. I name it this as Z is the last letter in the alphabet. This ensure’s it appears last in the folder listing as I have my listings by name.

Within the boilerplate folder ZZ I have:

  • cms
  • css
  • images
  • index.html
  • js
  • PIE
  • robots.txt
  • ZZ
    • Backups
      • Live
      • Local
    • Documents
    • Fonts
    • Images
    • Misc
    • Quote
    • Research
      • Images
    • Site
    • Sitemap
      • Visuals

Breakdown of Structure

At the start of each project I duplicate the ZZ folder in the Site’s folder and rename it to the name of the site I am building.

The Root

This folder if accessed using localhost will contain a working copy of the clients site in flat HTML format. The entire site is built unless it’s content managed. I build all the required HTML templates needed.

cms: As nearly all sites we build are content managed, I run a local copy of the site in it’s cms from within this folder.

images, css, js, PIE: these are all relevant to the flat HTML files. The images folder contains the images for the templates. CSS contains the stylesheets for the website. JS contain the javascript files if any is used, and PIE contains the latest copy of CSS3PIE.

The ZZ Folder

I am passed a set of visuals from the designer which I stick within the Visuals folder.

If any web fonts have been used, I stick these within the Font’s folder. If the font’s are not from Google or another online service I generate a font-face kit and also put this within the Fonts folder.

Along with a set of visuals, I also get a copy of the agreed sitemap and put this in the Sitemap folder. I find it much easier to work with a sitemap and a set of visuals, rather than scrolling up and down through a set of visuals.

The Documents folder will contain only relevant content/ documents needed for the site build. Sometimes I get given the entire site laid out in visuals, and other times I get just the different templates with the site content in a document.

The Images folder is for images as you can tell, this folder can get pretty big with some sites as this folder contains all original images for the site. Any images the client passes over or any images we purchase for them is kept here.

Misc: this, as the title says, is for any Miscellaneous items that do not fit into any of the other folders.

Quote: Sometimes I get a copy of the quote for reference and this is put here. This folder is also used in the future to store quotes for any additional work that needs quoting for.

Research: If I have done the research document it will live here, and the images folder within will contain images related to the research, like screenshots