10 Essential Principles of the Javascript Masters

Sep 22nd in JavaScript & AJAX by Glen Stansberry

JavaScript is one of the most widely used languages in web development. It's simple, yet very powerful, and the number of ways that it can be used are almost limitless. That's why it's so important to gather advice from those who have gone before you. Here are 10 tips from well-respected web developers within the JavaScript community.

PG

Author: Glen Stansberry

Glen Stansberry is a web developer and blogger. You can read more tips on web development at his blog Web Jackalope or follow him on Twitter.

1. Don't Overlook Binding - Christophe Porteneuve

Christophe Porteneuve has some serious designing chops. He's been developing websites since 1995, has run the software engineering department of a major IT college, and he's now the CTO of Ciblio.net. He's so good at what he does that the team at A List Apart has given him some screen real estate to share some of his insights.

Christophe hits upon a very important facet of javascript: Bindings.

Almost no major object-oriented programming (OOP) languages force you to consider binding. That is, they don’t require you to explicitly qualify access to the current object’s members (methods and properties) with a reference such as this or self. If you’re calling a method on no particular object, you’re usually calling it on the current object. The same goes when you’re passing a method around for later invocation: it will retain its current object. In short, for most OOP languages, binding is implicit.

Christophe goes on to give examples of proper binding, and how to recognize binding sensitive patterns. Here are four takeaway points in Christophe's article:

  • Any member access must be qualified with the object it pertains to, even when it is this.
  • Any sort of function reference (assigning as a value, passing as an argument) loses the function‚Äôs original binding.
  • JavaScript provides two equivalent ways of explicitly specifying a function‚Äôs binding when calling it: apply and call.
  • Creating an ‚Äúbound method reference‚Äù requires an anonymous wrapper function, and a calling cost. In specific situations, leveraging closures may be a better alternative.

2. Use JavaScript libraries instead of Flash or other animation - Dave Shea

Dave Shea is a respected web developer and designer, probably best known for his excellent work on CSS Zen. Dave has shown incredible capacity for designing exceptional user interfaces, and is another writer for the excellent A List Apart.

JavaScript libraries are like a Swiss Army knife for the Web developer. There are countless flavors of JavaScript libraries to choose from, and number of developers developing plug-ins for these libraries are growing daily. You can use JavaScript libraries for nearly any functionality.

Take CSS sprites, for example. Instead of using heavy flash layouts to achieve a rollover effect, Dave Shea believes that you should a use tiny JavaScript libraries like jQuery to pull off the same functionality. Dave lists some of the benefits of using JavaScript libraries, especially those hosted by Google.

Because many other web developers will be linking to the Google code, there is a chance that the JavaScript is already in the browser's cache. Using JavaScript libraries will allow you to focus more time on development, with less time spent writing JavaScript code.

3. Write JavaScript with micro-templates - John Resig

John Resig is one of the most popular JavaScript developers on the planet. He created the wildly popular JavaScript library jQuery. He's written a book on Pro JavaScript Techniques, and even shares his scripting knowledge on his personal blog.

John gives a rather unique method for speeding up JavaScript development time with the use of micro-templates.

I've had a little utility that I've been kicking around for some time now that I've found to be quite useful in my JavaScript application-building endeavors. It's a super-simple templating function that is fast, caches quickly, and is easy to use. I have a couple tricks that I use to make it real fun to mess with.

While using micro-templates isn't mission critical, it can really speed up the development process. Check out some of John's examples of micro-templating to get a better feel of the benefits of the templating function.

4. Bind Methods To Objects - Ayman Hourieh

Ayman Hourieh is a computer science graduate, Google employee and an author on Django web development. Ayman knows his way with elegant programming.

In his article outlining nine JavaScript tips, Ayman touches on a slightly more advanced aspect of binding methods to objects.

Anyone who works with JavaScript events may have come across a situation in which they need to assign an object's method to an event handler. The problem here is that event handlers are called in the context of their HTML element, even if they were originally bound to another object. To overcome this, I use a function that binds a method to an object; it takes an object and method, and returns a function that always calls the method in the context of that object.

By using Prototype and a little custom code, Ayman provides a great tip for binding methods to objects. A small, simple, and efficient trick.

5. Rely on event delegation - Andrew Tetlaw

Andrew Tetlaw has been developing websites since 1997, and is the technical editor for SitePoint. SitePoint wouldn't hire just any slouch to become their technical editor. Andrew's writing at SitePoint is proof of that.

Using JavaScript interactivity in your layouts can be a daunting task. But Andrew has shown that using event delegation is not only easier than you might think, but also provides many benefits like eliminating memory leaks.

JavaScript events are the bedrock of all interactivity on web pages (I mean serious interactivity, not those dinky CSS drop-down menus). In traditional event handling you add or remove event handlers from each element as needed. However, event handlers can potentially cause of memory leaks and performance degradation — the more you have, the greater the risk. JavaScript event delegation is a simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.

Many of the major JavaScript libraries have examples of event delegation, so you won't have to go write your own custom script.

6. Know when to use event delegation - Chris Heilmann

Chris Heilmann is an international development evangelist who works for the Yahoo Developer Network. Chris has some major JavaScript chops, and you can see many live presentations from his personal website.

Chris has developed an excellent tutorial that shows the differences between Event Delegation and Event Handling.

The difference between the two of them is that the "Handlers" example is rather slow when the list is very large while the "Delegation" example can be extended as much as you want to without adding more overhead. The latter example is also a lot easier to change.

Event Delegation is better suited for larger applications, while Event Handling is much more suited towards small projects.

For really small event handling efforts, the classic solution gives you more control and it is pretty easy to hand over to other developers without much explanation. Event delegation however is probably the only way to keep a large app with a lot of elements to apply handling to (or dynamically loaded elements) in check.

7. Make AJAX responses cacheable - YUI team

If there ever were a team of " JavaScript masters", the Yahoo! Developer Network might be it. The Yahoo! Developer team has provided some incredible assets to the development community. They feature extensive articles and tips from their own developers, so we can be assured that every bit of knowledge they share passes a very high standard.

Ajax can be a wonderful tool to provide a much richer user experience to a website. However, trade-off to using Ajax is that sometimes it loads slower than a traditional website. The Yahoo developer team has developed some tips on working with JavaScript and Ajax, specifically with caching Ajax so the response times are much faster.

In many applications, whether or not the user is kept waiting depends on how Ajax is used. For example, in a web-based email client the user will be kept waiting for the results of an Ajax request to find all the email messages that match their search criteria. It's important to remember that "asynchronous" does not imply "instantaneous".

To improve performance, it's important to optimize these Ajax responses. The most important way to improve the performance of Ajax is to make the responses cacheable...

Caching Ajax calls with methods like adding an Expires or a Cache-Control Headercan greatly speed up the application response times.

8. Put scripts at the bottom of the page - YUI

It's no surprise that the YUI team is going to make this list twice, with their wide knowledge base of JavaScript tips.

One simple yet key aspect of developing with JavaScript that many developers overlook is adding JavaScript at the bottom of the page, as opposed to the top. By adding JavaScript includes at the top of the page, you're blocking parallel downloads of other elements within the page too, like images.

It's not always the best idea to add JavaScript includes at the bottom, but many times you can, and your performance will increase because of it.

9. Don't use the Eval constructor - Julien Lecomte

Julien Lecomte is yet another Yahoo! Developer Network employee. He's a very knowledgeable man when it comes to optimizing JavaScript code as he has authored the YUI Compressor as well as the YUI History Manager.

In a talk given by Julien, he gives some excellent advice on JavaScript optimization. During the presentation Julien states that JavaScript programmers should stay as far away from the Eval constructor as possible. On slide 19 of the speech you'll see his rationale.

  • The string passed to Eval (and its relatives, the Function constructor and the setTimeout and setInterval functions) needs to be compiled and interpreted. Extremely slow!
  • Never pass a string to the setTimeout and setInterval functions. Instead pass an anonymous function.
  • Never use Eval and the Function constructor (except in some extremely rare cases, and only in code blocks where performance is not critical).

10. Assignment versus equality operators - Peter-Paul Koch

Peter-Paul Koch is a popular Apple Internet developer who also runs the Quirksmode website featuring oodles of JavaScript tips. Peter-Paul has also written the ppk on JavaScript, which features all sorts of information on great JavaScript development.

PPK touches on a major (and common) misunderstanding that new Java script writers might come across frequently: = or == ?

A mistake novel JavaScripters frequently make is confusing the assignment and equality operators = and ==. If you want to compare two values, you should use a double equal sign since that's how JavaScript works. If you accidentally use a single equal sign, you don't compare values but assign a value to a variable.

While not an earth shattering concept or tidbit of information, it's a helpful reminder that can save many hours for the beginning programmer.

  • Subscribe to the NETTUTS RSS Feed for more daily web development tutorials and articles.

Glen Stansberry is a web developer and blogger who's struggled more times than he'd wish to admit with CSS. You can read more tips on web development at his blog Web Jackalope.

If you found this post useful, please say thank you with a Digg:


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

Plus Members

Source Files, Bonus Tutorials and
More for $9 a month for all TUTS+
sites in one subscription.

Join Now

User Comments

( ADD YOURS )
  1. PG

    Jake Holman September 22nd

    Can’t possibly express more how much I love these articles – learning from multiple, solid sources is 100% better, in my opinion, than a lot of the ’solo’ articles. Thanks!

    ( Reply )
  2. PG

    Jayphen September 22nd

    Nice article, but what’s with all the spacey images?

    ( Reply )
  3. PG

    Keith September 22nd

    Fantastic piece! Nettuts is becoming bigger and bigger :)

    ( Reply )
  4. PG

    Aditya September 22nd

    Well, I don’t agree with Jake. We all want the best of both worlds, though these killer tips are useful, they can’t really replace the importance of solid, full-fledged tutorials.

    ( Reply )
  5. PG

    shag September 22nd

    so how do I know when to place a script or include at the bottom of the page and when is it not a good idea?

    ( Reply )
  6. PG

    chris September 22nd

    Douglas Crockford didn’t make the list? Rather than reaching on #10, any Crockford gem would have sufficed.

    ( Reply )
  7. PG

    Lamin Barrow September 22nd

    Very valuable post. Thanks very much

    ( Reply )
  8. PG

    insic September 22nd

    wow i didnt know some in the list. Great post!

    ( Reply )
  9. PG

    Shane September 23rd

    Good list with some pro-level JavaScript recommendations. It’s so great to see that JavaScript has matured such a lot over the last few years and we’re using great frameworks and practices.

    @Jayphen – good question. They’re nice though.

    ( Reply )
  10. PG

    Jake Holman September 23rd

    @Keith – I think it’s just the Wordpress Article Template they use, other than that it’s a nice break from images of code ;)

    @Aditya – I wasn’t arguing that the tutorials shouldn’t exist (hell I use em!) I was just stating that I feel more benefit from these!

    ( Reply )
  11. PG

    Ben Griffiths September 23rd

    Very useful tips, thans :)

    ( Reply )
  12. PG

    James September 23rd

    Good list, although I am surprised that there’s nothing from the only real JavaScript master, Doug Crockford…

    ( Reply )
  13. PG

    Jammin September 23rd

    I like the space images :)

    ( Reply )
  14. PG

    Dainis Graveris September 23rd

    ..and I thought that I will click at image and see different codes in live..:) Huh, nice tips!

    ( Reply )
  15. PG

    simplechris September 23rd

    good article… honestly never thought about the loading issue with JS included at the top of files… great stuff.

    ( Reply )
  16. PG

    Shane September 23rd

    @James – I hadn’t heard of Doug Crockford before. That’s not to say he isn’t a master, of course, but I don’t think you can really say he’s the only master.

    ( Reply )
  17. PG

    matt September 23rd

    One of the selling points of Chrome is that #8 will no longer be relevant. Multithreading is used to concurrently execute Javascript and render the page.

    ( Reply )
  18. PG

    Bill Biwer September 23rd

    Great post topic, a little past my .js level but I know where to look for the future.

    Nice imagery!

    ( Reply )
  19. PG

    ericb September 23rd

    great source of inspiration. THANKS!

    ( Reply )
  20. PG

    Kevin Quillen September 23rd

    John Resig? Fuchs?

    ( Reply )
  21. PG

    Kevin Quillen September 23rd

    My bad. I seemed to have missed Resig’s.

    #10 seems kinda basic though.

    ( Reply )
  22. PG

    Evan September 23rd

    Event delegation blew my mind when I first discovered the concept.

    Not only is it great for performance but it also comes in handy if you are using ajax to update the page. Rather than constantly having to add and remove events each time you update the dom you can rely on event delegation. You only ever have to create a single event. It seems to perform well, there is less chance of memory leaks and it is less work for the developer.

    ( Reply )
  23. PG

    Michael Thompson September 23rd

    I love the space images. I know there was some flak for another recent ‘Tuts article using non-related imagery, but I absolutely love it.

    ( Reply )
  24. PG

    Louis September 23rd

    Never thought of cachable ajax responses. Nice list though!

    ( Reply )
  25. PG

    Miles Johnson September 23rd

    I always think examples teach more then actually articles. A beginner wouldnt understand most of this.

    Also please stop with decorating posts with a ton of images, its pointless and takes your eyes of the actual article.

    ( Reply )
  26. PG

    Pedro September 23rd

    Always great to get tips for JS.

    Point 8 – Like this idea! Will try…

    ( Reply )
  27. PG

    Oluseyi September 23rd

    >> Almost no major object-oriented programming (OOP) languages force you to consider binding.
    >> That is, they don’t require you to explicitly qualify access to the current object’s members
    >> (methods and properties) with a reference such as this or self.

    Python.

    ( Reply )
  28. PG

    Mark September 23rd

    #10 should not be on this list. Why? It’s not essential to JavaScript, it’s essential to most programming languages.

    ( Reply )
  29. PG

    James September 24th

    I think #10 is pointless. If a beginner was to open up this post they would give up before reaching number 10! Plus I think a more useful tip would be specifically on the equality operator and how it’s good p[ractice to check for type as well as equality by using === instead of ==.

    I picked up #8 about a year ago and I’d just like to re-iterate its importance to those who continually insist on using window.onload or DOM-ready functions and putting function calls at the top of the page. “window.onload” should only ever be used when the script you are initiating requires all assets of the page to be loaded. DOM-ready functions are a bit heavy and quite slow… it’s quicker to just place your function calls at the bottom of the page… There is the added bonus of a quicker load time if you do this too!

    While #2 is good advice JavaScript *cannot* achieve everything that flash can. If all you want is the odd animation and fading navigation etc. then definitely take this advice and use JavaScript but for more complex animations/functionality Flash may be necessary.

    @Glen – Maybe with your next 10-feature list you could try and ease the reader in instead of starting with a complex topic and finishing with a simple one (#10)… Also, what is with all the images, they’re so big they kinda get in the way!

    ( Reply )
  30. PG

    karthik September 24th

    COOL

    ( Reply )
  31. PG

    JPH September 24th

    Good stuff – lots we can take away from this.

    ( Reply )
  32. PG

    Evan September 24th

    Awesome, I’m not the only person who uses JavaScript for animations!

    ( Reply )
  33. PG

    website designs September 24th

    10 uncommon tips from JavaScript legends.

    ( Reply )
  34. PG

    Takumi86 September 24th

    Nice artisitic picture but i don know if the word above the pic are .. relevant?!

    ( Reply )
  35. PG

    sam September 26th

    Great article, thanks for posting. A co-worker sent this to me and specifically mentioned the micro-templating mechanism. Cool stuff.

    http://www.samalamadingdong.com

    ( Reply )
  36. PG

    Cohen October 7th

    @Matt: it’s not the processing that’s blocked but the downloading. HTTP recommendation specifies that only 2 simultanious connections to the same domain should be maintained. So by placing the javascript lower you let the page first load all UI elements and then load javascript files. Which makes it seem as if the page is loaded faster. So still viable for google’s chrome, i think.

    Some great tips in there, but I agree about Crockford missing, I mean come on guys the creator of JsLint?

    ( Reply )
  37. PG

    BEvans October 13th

    Great Read, however, there are a lot of spelling errors that should have been fixed before publishing this article… looks like someone just copied and pasted stuff, but did not take the time to fix the typos that happen when using an microsoft application like “word”

    ( Reply )
  38. PG

    Ryan October 26th

    VERY nice!

    ( Reply )
  39. PG

    Lam Nguyen October 26th

    Thanks a lot about this entry, i’ll try it

    ( Reply )
  40. PG

    Rozzy February 25th

    How about actually learning the language and not a library? As the language and supported implementations improve, those libraries will become obsolete. Happy updating :P

    ( Reply )
  41. PG

    Adam Winogrodzki April 19th

    Great Post Loved reading it , LOL @ Spelling mistakes

    ( Reply )
  42. PG

    chic May 20th

    lol. I can’t believe = vs. == is one of the 10 essential principles of javascript masters!

    ( Reply )
  1. Arrow
    Gravatar

    Your Name
    May 20th