RSS
 

Posts Tagged ‘JavaScript’

Behind The Scenes Of Nike Better World

12 Jul

Advertisement in Behind The Scenes Of Nike Better World
 in Behind The Scenes Of Nike Better World  in Behind The Scenes Of Nike Better World  in Behind The Scenes Of Nike Better World

Perhaps one of the most talked about websites in the last 12 months has been Nike Better World. It’s been featured in countless Web design galleries, and it still stands as an example of what a great idea and some clever design and development techniques can produce.

In this article, we’ll talk to the team behind Nike Better World to find out how the website was made. We’ll look at exactly how it was put together, and then use similar techniques to create our own parallax scrolling website. Finally, we’ll look at other websites that employ this technique to hopefully inspire you to build on these ideas and create your own variation.

Nike Better World

Nike-Better-World in Behind The Scenes Of Nike Better World

Nike Better World is a glimpse into how Nike’s brand and products are helping to promote sports and its benefits around the world. It is a website that has to be viewed in a browser (preferably a latest-generation browser, although it degrades well) rather than as a static image, because it uses JavaScript extensively to create a parallax scrolling effect.

A good deal of HTML5 is used to power this immersive brand experience and, whatever your views on Nike and its products, this website has clearly been a labor of love for the agency behind it. Although parallax scrolling effects are nothing new, few websites have been able to sew together so many different design elements so seamlessly. There is much to learn here.

An “Interactive Storytelling Experience”

In our opinion, technologies are independent of concept. Our primary focus was on creating a great interactive storytelling experience.

– Widen+Kennedy

Nike turned to long-time collaborator Widen+Kennedy (W+K), one of the largest independent advertising agencies in the world, to put together a team of four people who would create Nike Better World: Seth Weisfeld was the interactive creative director, Ryan Bolls produced, while Ian Coyle and Duane King worked on the design and interaction.

Wiedenkennedy in Behind The Scenes Of Nike Better World

I started by asking the team whether the initial concept for the website pointed to the technologies they would use. As the quote above reveals, they in fact always start by focusing on the concept. This is a great point. Too many of us read about a wonderful new technique and then craft an idea around it. W+K walk in the opposite direction: they create the idea first, and sculpt the available technologies around it.

So, with the concept decided on, did they consciously do the first build as an “HTML5 website,” or did this decision come later?

There were some considerations that led us to HTML5. We knew we wanted to have a mobile- and tablet-friendly version. And we liked the idea of being able to design and build the creative only once to reach all the screens we needed to be on. HTML5 offered a great balance of creativity and technology for us to communicate the Nike Better World brand message in a fresh and compelling way.

– W+K

HTML5 is still not fully supported in all browsers (read “in IE”) without JavaScript polyfills, so just how cross-browser compatible did the website have to be?

The primary technical objectives were for the site to be lightweight, optimized for both Web and devices, as well as to be scalable for future ideas and platforms.

– W+K

To achieve these goals, the website leans on JavaScript for much of the interactivity and scrolling effects. Later, we’ll look at how to create our own parallax scrolling effect with CSS and jQuery. But first, we should start with the template and HTML.

The Starting Boilerplate

It’s worth pointing out the obvious first: Nike Better World is original work and should not be copied. However, we can look at how the website was put together and learn from those techniques. We can also look at other websites that employ parallax scrolling and then create our own page, with our own code and method, and build on these effects.

I asked W+K if it starts with a template.

We started without a framework, with only reset styles. In certain cases, particularly with experimental interfaces, it ensures that complete control of implementation lies in your hands.

– W+K

If you look through some of the code on Nike Better World, you’ll see some fairly advanced JavaScript in a class-like structure. However, for our purposes, let’s keep things fairly simple and rely on HTML5 Boilerplate as our starting point.

Download HTML5 Boilerplate. The “stripped” version will do. You may want to delete some files if you know you won’t be using them (crossdomain.xml, the test folder, etc.).

As you’ll see from the source code (see the final code below), our page is made up of four sections, all of which follow a similar pattern. Let’s look at one individual section:

<section class="story" id="first" data-speed="8" data-type="background">
 <div data-type="sprite" data-offsetY="950" data-Xposition="25%" data-speed="2"></div>
 <article>
  <h2>Background Only</h2>
  <div>
   <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
  </div>
 </article>
</section>

I’m not sure this is the best, most semantic use of those HTML5 tags, but it’s what we need to make this effect work. Normally, a section has a heading, so, arguably, the section should be a div and the article should be a section. However, as W+K points out, the HTML5 spec is still young and open to interpretation:

HTML5 is still an emerging standard, particularly in implementation. A lot of thought was given to semantics. Some decisions follow the HTML5 spec literally, while others deviate. As with any new technology, the first to use it in real-world projects are the ones who really shape it for the future.

– W+K

This is a refreshing interpretation. Projects like Nike Better World are an opportunity to “reality check” an emerging standard and, for the conscientious among us, to provide feedback on the spec.

In short, is the theory of the spec practical? W-K elaborates:

We use the article tag for pieces of content that can (and should) be individually (or as a group) syndicated. Each “story” is an article. We chose divs to wrap main content. We took the most liberty with the section tag, as we feel its best definition in the spec is as chapters of content, be it globally.

– W+K

As an aside (no pun intended!), HTML5 Doctor has begun a series of mark-up debates called Simplequizes, which are always interesting and illustrate that there is rarely one mark-up solution for any problem. Make sure to check them out.

In style.css, we can add a background to our section with the following code:

section { background: url(../images/slide1a.jpg) 50% 0 no-repeat fixed; }

We should also give our sections a height and width, so that the background images are visible:

.story { height: 1000px; padding: 0; margin: 0; width: 100%; max-width: 1920px; position: relative; margin: 0 auto; }

I’ve set the height of all our sections to 1000 pixels, but you can change this to suit your content. You can also change it on a per-section basis.

We have also made sure that the maximum width of the section is the maximum width of the background (1920 pixels), and we have specified a relative position so that we can absolutely position its children.

Here’s the page before adding JavaScript. It’s worth digging into the source code to see how we’ve duplicated the sections in the HTML and CSS.

Backgroundonly in Behind The Scenes Of Nike Better World

Even with this code alone, we already have a pleasing effect as we scroll down the page. We’re on our way.

The HTML5 Data Attribute

Before looking at parallax scrolling, we need to understand the new data attribute, which is used extensively throughout the HTML above.

Back in the good old days, we would shove any data that we wanted to be associated with an element into the rel attribute. If, for example, we needed to make the language of a story’s content accessible to JavaScript, you might have seen mark-up like this:

<article class='story' id="introduction" rel="en-us"></article>

Sometimes complex DOM manipulation requires more information than a rel can contain, and in the past I’ve stuffed information into the class attribute so that I could access it. Not any more!

The team at W+K had the same issue, and it used the data attribute throughout Nike Better World:

The data attribute is one of the most important attributes of HTML5. It allowed us to separate mark-up, CSS and JavaScript into a much cleaner workflow. Websites such as this, with high levels of interaction, are almost application-like behind the scenes, and the data attribute allows for a cleaner application framework.

– W+K

Sportisanaddress in Behind The Scenes Of Nike Better World

So, what is the data attribute? You can read about it in the official spec, which defines it as follows:

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

– W+K

In other words, any attribute prefixed with data- will be treated as storage for private data; it does not affect the mark-up, and the user cannot see it. Our previous example can now be rewritten as:

<article class='story' id="introduction" data-language="en-us"></article>

The other good news is that you can use more than one data attribute per element, which is exactly what we’re doing in our parallax example. You may have spotted the following:

<div data-type="sprite" data-offsetY="100" data-Xposition="50%" data-speed="2"></div>

Here, we are storing four pieces of information: the x and y data offsets and the data speed, and we are also marking this element as a data type. By testing for the existence of data-type in the JavaScript, we can now manipulate these elements as we wish.

Parallax Scrolling

On our page, three things create the parallax scrolling illusion:

  • The background scrolls at the slowest rate,
  • Any sprites scroll slightly faster than the background,
  • Any section content scrolls at the same speed as the window.

With three objects all scrolling at different speeds, we have created a beautiful parallax effect.

AnExplanation in Behind The Scenes Of Nike Better World

It goes without saying that we don’t need to worry about the third because the browser will take care of that for us! So, let’s start with the background scroll and some initial jQuery.

$(document).ready(function(){
 // Cache the Window object
 $window = $(window);
// Cache the Y offset and the speed
$('[data-type]').each(function() {
  $(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
  $(this).data('speed', $(this).attr('data-speed'));
});
// For each element that has a data-type attribute
 $('section[data-type="background"]').each(function(){
  // Store some variables based on where we are
  $(this).data('speed', parseInt($(this).attr('data-speed')));
   var $self = $(this),
   offsetCoords = $self.offset(),
   topOffset = offsetCoords.top;
   $(window).scroll(function(){
    // The magic will happen in here!
   }); // window scroll
 });	// each data-type
}); // document ready

First, we have our trusty jQuery document ready function, to ensure that the DOM is ready for processing. Next, we cache the browser window object, which we will refer to quite often, and call it $window. (I like to prefix jQuery objects with $ so that I can easily see what is an object and what is a variable.)

We also use the jQuery .data method to attach the Y offset (explained later) and the scrolling speed of the background to each element. Again, this is a form of caching that will speed things up and make the code more readable.

We then iterate through each section that has a data attribute of data-type="background" with the following:

$('section[data-type="background"]').each(function(){}

Already we can see how useful data attributes are for storing multiple pieces of data about an object that we wish to use in JavaScript.

Inside the .each function, we can start to build up a picture of what needs to be done. For each element, we need to grab some variables:

// Store some variables based on where we are
var $self = $(this),
    offsetCoords = $self.offset(),
    topOffset = offsetCoords.top;

We cache the element as $self (again, using the $ notation because it’s a jQuery object). Next, we store the offset() of the element in offsetCoords and then grab the top offset using the .top property of offset().

Finally, we set up the window scroll event, which fires whenever the user moves the scroll bar or hits an arrow key (or moves the trackpad or swipes their finger, etc.).

We need to do two more things: check that the element is in view and, if it is, scroll it. We test whether it’s in view using the following code:

// If this section is in view
if ( ($.Window.scrollTop() + $.Window.height()) > ($offsetCoords.top) &&
( ($offsetCoords.top + $self.height()) > $.Window.scrollTop() ) ) {
}

The first condition checks whether the very top of the element has scrolled into view at the very bottom of the browser window.

The second condition checks whether the very bottom of the element has scrolled past the very top of the browser window.

You could use this method to check whether any element is in view. It’s sometimes useful (and quicker) to process elements only when the user can see them, rather than when they’re off screen.

So, we now know that some part of the section element with a data-type attribute is in view. We can now scroll the background. The trick here is to scroll the background slower or faster than the browser window is scrolling. This is what creates the parallax effect.

Here’s the code:

// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -($window.scrollTop() / $self.data('speed'));

// If this element has a Y offset then add it on
if ($self.data('offsetY')) {
  yPos += $self.data('offsetY');
}

// Put together our final background position
var coords = '50% '+ yPos + 'px';

// Move the background
$self.css({ backgroundPosition: coords });

The y position is calculated by dividing the distance that the user has scrolled from the top of the window by the speed. The higher the speed, the slower the scroll.

Next, we check whether there is a y offset to apply to the background. Because the amount that the background scrolls is a function of how far the window has scrolled, the further down the page we are, the more the background has moved. This can lead to a situation in which the background starts to disappear up the page, leaving a white (or whatever color your background is) gap at the bottom of each section.

The way to combat this is to give those backgrounds an offset that pushes them down the page an extra few hundred pixels. The only way to find out this magic offset number is by experimenting in the browser. I wish it was more scientific than this, but this offset really does depend on the height of the browser window, the distance scrolled, the height of your sections and the height of your background images. You could perhaps write some JavaScript to calculate this, but to me this seems like overkill. Two minutes experimenting in Firebug yields the same result.

The next line defines a variable coords to store the coordinates of the background. The x position is always the same: 50%. This was the value we set in the CSS, and we won’t change it because we don’t want the element to scroll sideways. Of course, you’re welcome to change it if you want the background to scroll sideways as the user scrolls up, perhaps to reveal something.

(Making the speed a negative number for slower scrolling might make more sense, but then you’d have to divide by -$speed. Two negatives seems a little too abstract for this simple demonstration.)

Finally, we use the .css method to apply this new background position. Et voila: parallax scrolling!

Here’s the code in full:

// Cache the Window object
$window = $(window);

// Cache the Y offset and the speed of each sprite
$('[data-type]').each(function() {
  $(this).data('offsetY', parseInt($(this).attr('data-offsetY')));
  $(this).data('speed', $(this).attr('data-speed'));
});

// For each element that has a data-type attribute
$('section[data-type="background"]').each(function(){

// Store some variables based on where we are
var $self = $(this),
    offsetCoords = $self.offset(),
    topOffset = offsetCoords.top;

$(window).scroll(function(){

// If this section is in view
if ( ($window.scrollTop() + $window.height()) > (topOffset) &&
( (topOffset + $self.height()) > $window.scrollTop() ) ) {

  // Scroll the background at var speed
  // the yPos is a negative value because we're scrolling it UP!
  var yPos = -($window.scrollTop() / $self.data('speed'));

  // If this element has a Y offset then add it on
  if ($self.data('offsetY')) {
    yPos += $self.data('offsetY');
  }

  // Put together our final background position
  var coords = '50% '+ yPos + 'px';

  // Move the background
  $self.css({ backgroundPosition: coords });

  }; // in view

}); // window scroll

});	// each data-type

Of course, what we’ve done so far is quite a bit simpler than what’s on Nike Better World. W+K admits that the parallax scrolling threw it some challenges:

The parallax scrolling presented a few small challenges in cross-browser compatibility. It took a little experimenting to ensure the best scrolling experience. In the end, it was less about the actual parallax effect and more about synchronized masking of layers during transitions.

– W+K

W+K also reveals how it maintained a fast loading and paint speed by choosing its tools wisely:

The key to maintaining faster speeds is to use native CSS where possible, because DOM manipulation slows down rendering, particularly on older browsers and processors.

– W+K

For example, the “More” button below spins on hover, an effect achieved with CSS3. In browsers that don’t support CSS3 transforms, the purpose of the graphic is still obvious.

CSSuse in Behind The Scenes Of Nike Better World

Adding More Elements

Of course, one of the other common features of parallax scrolling is that multiple items on the page scroll. So far, we have two elements that move independently of each other: the first is the page itself, which scrolls when the user moves the scroll bar, and the second is the background, which now scrolls at at slower rate thanks to the jQuery above and the background-position CSS attribute.

For many pages, this would be enough. It would be a lovely effect for the background of, say, a blog. However, Nike and others push it further by adding elements that move at a different speed than that of the page and background. To make things easy — well, easier — I’m going to call these new elements sprites.

Here’s the HTML:

<div id="smashinglogo" data-type="sprite" data-offsetY="1200" data-Xposition="25%" data-speed="2"></div>

Put this just before the closing </article> tag, so that it appears behind the contents of <article>. First, we give the div an id so that we can refer to it specifically in the CSS. Then we use our HTML5 data attribute to store a few values:

  • The status of a sprite,
  • A y (vertical) offset of 1200 pixels,
  • An x (horizontal) position as a percentage,
  • A scrolling speed.

We give the x position of the sprite a percentage value because it is relative to the size of the viewport. If we gave it an absolute value, which you’re welcome to try, there’s a chance it could slide out of view on either the left or right side.

Now about that y offset…

Inception

This is the bit that’s going to mess with your noodle and is perhaps the hardest part of the process to grasp.

Thanks to the logic in the JavaScript, the sprite won’t move until the parent section is in view. When it does move, it will move at (in this case) half the speed. You need the vertical position, then, to account for this slower movement; elements need to be placed higher up if they will be scrolling more slowly and, therefore, moving less on the y axis.

We don’t know how far the user has to scroll before the section appears at the bottom of the page. We could use JavaScript to read the viewport size and then do some calculations based on how far down the page the section is positioned. But that is already sounding too complicated. There is an easier way.

What we do know is how far the user has scrolled before the current section is flush with the top of the viewport: they have scrolled the y offset of that particular section. (Put another way, they have scrolled the height of all of the elements above the current one.)

So, if there are four sections, each 1000 pixels high, and the third section is at the top of the viewport, then the user must have scrolled 2000 pixels, because this is the total height of the preceding sections.

If we want our sprite to appear 200 pixels from the top of its parent section, you’d figure that the total vertical offset we give it should be 2200 pixels. But it’s not, because this sprite has speed, and this speed (in our example) is a function of how far the page has been scrolled.

Let’s assume that the speed is set as 2, which is half the speed at which the page is scrolling. When the section is fully in view, then the window has scrolled 2000 pixels. But we divide this by the speed (2) to get 1000 pixels. If we want the sprite to appear 200 pixels from the top, then we need to add 200 to 1000, giving us 200 pixels. Therefore, the offset is 1200. In the JavaScript, this number is inverted to -1200 because we are pushing the background-position down off the bottom of the page.

Here’s a sketch to show this in action.

Parallax-sketch in Behind The Scenes Of Nike Better World

This is one of those concepts that is easier to understand when you view the page and source code and scroll around with the console open in Firebug or Developer Tools.

The JavaScript looks like this:

// Check for other sprites in this section
$('[data-type="sprite"]', $self).each(function() {

  // Cache the sprite
  $sprite = $(this);

  // Use the same calculation to work out how far to scroll the sprite
  var yPos = -($.Window.scrollTop() / $sprite.data('speed'));
  var coords = $sprite.data('Xposition') + ' ' + (yPos + $sprite.data('offsetY')) + 'px';
  $sprite.css({ backgroundPosition: coords });
}); // sprites

HTML5 Video

One criticism levelled at Nike Better World is that it didn’t use HTML5 video. HTML5 is still not fully supported across browsers (I’m looking at you, Internet Explorer), but for the purposes of this article, we’ll embrace HTML5 video, thanks to the lovely folks at Vimeo and Yum Yum London.

But we can’t set a video as a background element, so we have a new challenge: how to position and scroll this new sprite?

Well, there are three ways:

  1. We could change its margin-top property within its parent section;
  2. We could make it a position: absolute element and change its top property when its parent section comes into view;
  3. We could define it as position: fixed and set its top property relative to the viewport.

Because we already have code for the third, let’s grab the low-hanging fruit and adapt it to our purposes.

Here’s the HTML we’ll use, which I’ve placed after the closing </article> tag:

<video controls width="480" width="320" data-type="video" data-offsetY="2500" data-speed="1.5">
  <source src="video/parallelparking.theora.ogv" type="video/ogg" />
  <source src="video/parallelparking.mp4" type="video/mp4" />
  <source src="video/parallelparking.webm" type="video/webm" />
</video>

First, we’ve opened our HTML5 video element and defined its width and height. We then set a new data-type state, video, and defined our y offset and the speed at which the element scrolls. It’s worth nothing that some experimentation is needed here to make sure the video is positioned correctly. Because it’s a position: fixed element, it will scroll on top of all other elements on the page. You can’t cater to every viewport at every screen resolution, but you can play around to get the best compromise for all browser sizes (See “Bespoke to Broke” below).

The CSS for the video element looks like this:

video { position: fixed; left: 50%; z-index: 1;}

I’ve positioned the video 50% from the left so that it moves when the browser’s size is changed. I’ve also given it a z-index: 1. This z-index prevents the video element from causing rendering problems with neighbouring sections.

And now for the JavaScript! This code should be familiar to you:

// Check for any Videos that need scrolling
$('[data-type="video"]', $self).each(function() {

  // Cache the sprite
  $video = $(this);

  // Use the same calculation to work out how far to scroll the sprite
  var yPos = -($window.scrollTop() / $video.data('speed'));
  var coords = (yPos + $video.data('offsetY')) + 'px';

  $video.css({ top: coords });

}); // video

And there you have it! A parallax scrolling HTML5 video.

Bespoke or Broke

Of course, every design is different, which means that your code for your design will be unique. The JavaScript above will plug and play, but you will need to experiment with values for the y offset to get the effect you want. Different viewport sizes means that users will scroll different amounts to get to each section, and this in turn affects how far your elements scroll. I can’t control it any more than you can, so you have to pick a happy medium. Even Nike Better World suffers when the viewport’s vertical axis stretches beyond the height of the background images.

I asked W+K how it decides which effects to power with JavaScript and which are better suited to modern CSS techniques:

Key points that required complex interaction relied on JavaScript, while visual-only interactivity relied on CSS3. Additionally, fewer browsers support native CSS3 techniques, so items that were more important to cross-browser compatibility were controlled via JavaScript as well.

– W+K

This is a wonderful example of “real-world design.” So often we are bamboozled with amazing new CSS effects, and we make websites that sneer at older browsers. The truth is, for most commercial websites and indeed for websites like Nike Better World that target the biggest audience possible, stepping back and considering how best to serve your visitors is important.

W+K explains further:

We started by creating the best possible version, but always kept the needs of all browsers in mind. Interactive storytelling must balance design and technology to be successful. A great website usable in one or two browsers ultimately fails if you want to engage a wide audience.

– W+K

And Internet Explorer?!

IE was launched in tandem with the primary site. Only IE6 experienced challenges, and as a deprecated browser, it gracefully degrades.

– W+K

The Final Code

The code snippets in this piece hopefully go some way to explaining the techniques required for a parallax scrolling effect. You can extend them further to scroll multiple elements in a section at different speeds, or even scroll elements sideways!

Feel free to grab the full source code from GitHub, and adapt it as you see fit. Don’t forget to let us know what you’ve done, so that others can learn from your work.

Of course, remember that manipulating huge images and multiple sprites with JavaScript can have huge performance drawbacks. As Keith Clark recently tweeted:

KeithClark1 in Behind The Scenes Of Nike Better World

Test, test and test again. Optimize your images, and be aware that you may have to compromise to support all browsers and operating systems.

Tell A Story

Above and beyond the technical wizardry of parallax websites — some of the best of which are listed below — the common thread that each seems to embody is story. That’s what makes them great.

I asked W+K what it learned from the project:

That a strong voice, simplicity and beauty are integral to a great interactive storytelling experience. We often hear things like “content is king, and technology is just a tool to deliver it,” but when you’re able to successfully combine a powerful message with a compelling execution, it creates an experience that people really respond to and want to spend time with.

– W+K

We really have just scratched the surface of the work that goes into a website like Nike Better World. The devil is in the details, and it doesn’t take long to see how much detail goes into both the design and development.

However, if you have a compelling story to tell and you’re not afraid of a little JavaScript and some mind-bending offset calculations, then a parallax website might just be the way to communicate your message to the world.

More Examples

Nike wasn’t the first and won’t be the last. Here are some other great examples of parallax scrolling:

Manufacture d’essai

Manufacture-dEssai in Behind The Scenes Of Nike Better World

Yebo Creative

Yebocreative in Behind The Scenes Of Nike Better World

TEDx Portland

TEDxPortland1 in Behind The Scenes Of Nike Better World

Ben the Bodyguard

BenTheBodyguard in Behind The Scenes Of Nike Better World

Campaign Monitor Is Hiring

CampaignMonitor1 in Behind The Scenes Of Nike Better World

Nizo App

Nizo1 in Behind The Scenes Of Nike Better World

7 Best Things of 2010

7BestThings in Behind The Scenes Of Nike Better World

If you’ve seen or built a great parallax website, please let us know about it in the comments.

… If you need any more encouragement to create a website as compelling as these, here’s what the team at W+K used to put together Nike Better World: MacBook Air 13″, Canon 5D Mark II, Coda, Adobe Photoshop and Adobe Illustrator.

Thanks

Putting together this article took the cooperation of a number of people. I’d like to thank Seth, Ryan, Ian and Duane for answering my questions; Katie Abrahamson at W+K for her patience and for helping coordinate the interview; and Nike for allowing us to dissect its website so that others could learn.

(al)


© Richard Shepherd for Smashing Magazine, 2011.

 
 

7 Great JavaScript Resources

03 Jul


As browsers and server-side platforms advance, and libraries new and old grow and mature, JavaScript evolves as well. Staying at the top of your game is important. As a JavaScript developer, you’ll need to keep up with the latest news and learn new skills.

We’ve put together a list of seven of our favorite JavaScript resources to help save you time and energy along the way. Whether you’re a beginner or a seasoned pro, we think you’ll find the sites below both informative and beneficial. If you know of other great resources, feel free to share them in the comments.


1. Mozilla Developer Network




The MDN has become the de facto resource for JavaScript documentation, and is an excellent resource for beginners and seasoned developers alike. Here you'll find the official and complete JavaScript reference, as well as useful guides, tutorials and articles covering everything from the basics of how JavaScript works to its best practices and design patterns. The MDN also has a thorough DOM reference, which we highly recommend checking out as well.


2. JQAPI




JQAPI is an alternative to the official jQuery.com API documentation. If you're a client-side JavaScript developer, chances are you probably have used, or at some point will use, jQuery in at least one of your projects. Whether your use is occasional or daily, you'll want to keep up with the latest development and new features in JavaScript's most popular library. Each new release improves security and performance via a slick, responsive and intuitive interface for quick browsing and searching of jQuery documentation. The UI here really is top-notch, and as a bonus, there's an offline version available for download.


3. JS Fiddle




JS Fiddle is a JavaScript pastebin on steroids. Create, share, execute and test your JavaScript right in the browser. This is a great tool for collaborative debugging or for sharing code snippets. It's also a fun way to perform quick experiments and test out new ideas. Simply combine your JavaScript, HTML and CSS, then click the "Run" button to see the results. You can also validate your JavaScript code against JSLint and save your Fiddle for use later, or share with others. JS Fiddle provides a number of useful features, like the ability to load up common frameworks automatically (to test your jQuery or MooTools code, for example) and as-you-type syntax highlighting, just like you'd get by writing code in your favorite IDE.


4. Eloquent JavaScript




This free ebook is an introduction to programming and the JavaScript language, written by developer and tech writer Marjin Haverbeke. The book reads much like a tutorial, and introduces a number of concepts and real-world applications in a clean, concise style. Interactive examples are also available, which means you can read about various techniques. You'll also get a chance to see them in action, and tinker with the code yourself. We found a lot of positive reviews for this book, so if you're new to JavaScript, this is definitely a book worth checking out.


5. Douglas Crockford's JavaScript Videos




An undisputed expert in JavaScript, Douglas Crockford is Yahoo's JavaScript architect and is one of the individuals instrumental in the planning, development and future growth of the language. The videos and transcripts on the YUI blog derive from a series of talks given by Mr. Crockford about the history of JavaScript, its future and its use today. Though the series is now about a year and a half old, we still think you'll find the videos informative. We certainly recommend watching them for a better understanding of the language, where it's been, how it works and where it's going.


6. How To Node




Not all JavaScript development takes place in the browser. NodeJS is one of the web's most popular server-side JavaScript frameworks. Whether you're a seasoned Node developer or someone who's looking to add server-side JavaScript to his repertoire, How To Node offers a great collection of articles on NodeJS development. This community-driven site offers an excellent repository of Node tutorials that's proven itself useful on a number of occasions. No Node developer toolkit would be complete without it.


7. DailyJS




We've looked at some great tools and reference material, covered tutorials from our favorite libraries and frameworks and touched on both client and server-side JavaScript development. However, we're always searching for something new. DailyJS is a popular JavaScript-focused blog that brings you the latest and greatest JavaScript news, offers tips and techniques, and reviews libraries, plug-ins and services for JavaScript developers. If you're just itching for your daily dose of JavaScript goodness, DailyJS has you covered.

More About: design, dev, features, javascript, List, Lists, web design, Web Development

For more Dev & Design coverage:

 
 

For Your Script Loading Needs

15 Apr

Advertise here

As JavaScript usage has skyrocketed over the last few years, so has the sheer number of scripts that are being loaded in an average web page. With these script tags comes a lot of baggage, such as blocking and lack of dependency management.

Today, I’d like to bring your attention to a number of JavaScript loaders, which are mini toolkits that significantly simplify how you add and load scripts.


The Problem with Simple Script Tags

They Block the Page

The page stops ‘happening’ while the script is downloaded.

JavaScript files loaded using the script tag are blocking by nature. Everything that’s happening or loading on the page is halted while the script is downloaded and executed. And remember that this applies to each script tag. Some modern browsers may let you download these in parallel, but the rest of the page is still blocked from doing anything meaningful.

No Easy Way to Manage Dependencies

Lack of dependency management is a big drawback.

Next up comes the issue of handling dependencies. For your average web page, you probably don’t need one. Check if your library is loaded and move on. For a non-trivial web application though, this isn’t a great solution. You’ll need to load scripts conditionally based on dependencies. Even then, you’ll still have to figure out the order in which they’re loaded. You can probably do it manually for 3-4 files, but when things begin piling up, you’re probably better off with an automated solution.


Available Choices

The initial idea for this round up was sparked by a post over at Hacker News about making a list of JavaScript script loaders, roughly a month ago. I watched the list balloon up from 3 to a grand total of 10 before I lost interest and moved on.

Now that sufficient time has passed, I think that list is going to be quite massive. Unfortunately, my Google-fu is pretty weak and I can’t seem to find it. If an eagle eyed user manages to find this thread, post in the comments below so I can link to it and hopefully expand my list here as well.

This list is drawn from recommendations by high level web developers who use these tools in their applications.

And as to my choices here, this list represents a superset of recommendations which flowed in after I asked some of the front end community to pitch in with the solutions they’re using. Some of the solutions below may handle dependency managements too, though most stick to simple asynchronous loading. Regardless of the extra niceties, each of the scripts below do one thing with aplomb — load up JavaScripts with minimal fuss.

So without further ado, and in no particular order:


HeadJS

Head JS loads scripts in parallel no matter how many of them and what the browser is. Load scripts like images. Use HTML5 and CSS3 safely. Target CSS for different screens, paths, states and browsers. Make it the only script in your HEAD.

Author: Tero Piirainen

Project URL: Here

Size: 6.3 KB

Related links:


LabJS

LABjs (Loading And Blocking JavaScript) is an all-purpose, on-demand JavaScript loader, capable of loading any JavaScript resource, from any location, into any page, at any time. You can easily specify which scripts have execution order dependencies and LABjs will ensure proper execution order. This makes LABjs safe to use for virtually any JavaScript resource, whether you control/host it or not, and whether it is standalone or part of a larger dependency tree of resources.

Author: Kyle Simpson

Project URL: Here

Size: 4.7 KB

Related links:


RequireJS

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Author: James Burke

Project URL: Here

Size: 13 KB

Related links:


ControlJS

ControlJS is a JavaScript module that handles both inline scripts and external scripts, delays script execution until after the page has rendered, allows for scripts to be downloaded, not executed and integrates with simple changes to HTML and no code changes

Author: Steve Souders

Project URL: Here

Size: 3.6 KB

Related links:


StealJS

The StealJS project is a collection of command and client based JavaScript utilities that make building, packaging, sharing and consuming JavaScript applications easy. Includes modules for dependency management, JS compression, cleaning and logging.

Author: Brian Moschel

Project URL: Here

Size: 11.4 KB

Related links:


yepnope

yepnope is an asynchronous conditional resource loader that’s super-fast, and allows you to load only the scripts that your users need. It works with both JavaScript and CSS and has a full test suite in QUnit that you can run in your set of supported browsers to make sure it works.

Author: Alex Sexton and Ralph Holzmann

Project URL: Here

Size: 3.4 KB

Related links:


PINF JS Loader

The loader allows for bootstrapping a consistent and state-of-the-art CommonJS environment for any supported platform (on server & in browser) and thus is ideally suited to be used as the target for the commonjs command and the development of cross-platform JavaScript applications and libraries.

Author: Christoph Dorn

Project URL: Here

Size: 22 KB

Related links:


JSLoad

JSLoad is a Javascript file loader that we wrote for Instructables. You give it a set of dependencies and groupings, and it loads the files you need, when your executing code needs them. The real usefulness of JSLoad comes with its ability to group dependencies using tags.

Author: Eric Nguyen

Project URL: Here

Size: 9.8 KB

Related links:


JsDefer

JsDefer features parallel/serial loading based on definitions, dependency, and wrapped versus unwrapped, and whether dependencies are defined in separate def file or in script itself and integration with Deferred (as in jQuery 1.5) enables or simplifies many use-case scenarios among many others.

Author: Boris Moore

Project URL: Here

Size: 4.7 KB

Related links:


JSL (JavaScript Loader)

JSL features on-demand loading, is browser cacheable, dynamic asynchronous JavaScript loading, lazy loading and duplicate source prevention among a ton of other features.

Author: Andres Vidal

Project URL: Here

Size: 2.1 KB

Related links:


YUI 3 Get

The Get Utility provides a mechanism for attaching script and css resources — including cross-domain resources — to the DOM after the page has loaded.

Author: Adam Moore

Project URL: Here

Size: 17.9 KB

Related links:


DominateJS

DominateJS allows you to asynchronously load all your JavaScript, and defer sequential execution until the page loads. DominateJS aims to be a cross-browser and 100% document.write-safe library! This is a heavily modified (and powerful!) evolution of ControlJS.

Author: Chris Joel & Jason Benterou

Project URL: Here

Size: 48 KB


Load.js

load.js is a micro JS lazy-loader. Built on top of chain.js, it allows you to lazy load your JS scripts sequentially or in parallel and handle complex dependency chains.

Author: Chris O’Hara

Project URL: Here

Size: 2 KB

Related links:


BravoJS

BravoJS is an implementation of a proposed draft for CommonJS Modules/2.0

Author: Wes Garland

Project URL: Here

Size: 10.7 KB


Bootstrap

Bootstrap is a small library for dynamically loading JavaScript files.
It’s primary use case is for using in your JS code to load JS files only when they are used.

Author: Scott Koon

Project URL: Here

Size: 1.3 KB


LazyLoad

LazyLoad is a tiny (only 904 bytes minified and gzipped), dependency-free JavaScript utility that makes it super easy to load external JavaScript and CSS files on demand.

Whenever possible, LazyLoad will automatically load resources in parallel while ensuring execution order when you specify an array of URLs to load. In browsers that don’t preserve the execution order of asynchronously-loaded scripts, LazyLoad will safely load the scripts sequentially.

Author: Ryan Grove

Project URL: Here

Size: 1.6 KB


curl.js

curl.js is a small, but very fast AMD-compliant asynchronous loader. Current size: 4.5KB (2.1KB gzipped) using Google’s Closure Compiler.

If you’d like to use curl.js for non-AMD modules (ordinary javascript files), you’ll want to use the version with the js! plugin built in. You may also want to build-in the domReady module. The combined curl+js+domReady loader is still only 6.1KB (2.7KB gzipped).

Author: John Hann

Project URL: Here

Size: 5 KB


$script.js

$script.js is an asynchronous JavaScript loader and dependency manager with an astonishingly impressive lightweight footprint. Like many other script loaders, $script.js allows you to load script resources on-demand from any URL and not block other resources from loading, like CSS and images.

Author: Dustin Diaz

Project URL: Here

Size: 1.4 KB


NBL.js

NBL.js is a tiny script that will make your HTML pages load faster by loading all your JavaScript files asynchronously (in parallel) with the rest of your page. Normally if you include two or three scripts in your page, the browser will wait for them to be executed before your page is shown.

Author: Berklee

Project URL: Here

Size: 971 B

Related links:


That’s a Wrap!

While each of the tools listed above handle script loading in slightly unique ways, be sure to perform your tests when deciding which is the right one for you.

As I mentioned earlier, if you think a loader should be here but isn’t, drop us a line below and we’ll update the roundup accordingly.

As JavaScript usage has skyrocketed over the last few years, so has the sheer number of scripts that are being loaded in an average web page. With these script tags comes a lot of baggage, such as blocking and lack of dependency management.

Today, I’d like to bring your attention to a number of JavaScript loaders, which are mini toolkits that significantly simplify how you add and load scripts.


The Problem with Simple Script Tags

They Block the Page

The page stops ‘happening’ while the script is downloaded.

JavaScript files loaded using the script tag are blocking by nature. Everything that’s happening or loading on the page is halted while the script is downloaded and executed. And remember that this applies to each script tag. Some modern browsers may let you download these in parallel, but the rest of the page is still blocked from doing anything meaningful.

No Easy Way to Manage Dependencies

Lack of dependency management is a big drawback.

Next up comes the issue of handling dependencies. For your average web page, you probably don’t need one. Check if your library is loaded and move on. For a non-trivial web application though, this isn’t a great solution. You’ll need to load scripts conditionally based on dependencies. Even then, you’ll still have to figure out the order in which they’re loaded. You can probably do it manually for 3-4 files, but when things begin piling up, you’re probably better off with an automated solution.


Available Choices

The initial idea for this round up was sparked by a post over at Hacker News about making a list of JavaScript script loaders, roughly a month ago. I watched the list balloon up from 3 to a grand total of 10 before I lost interest and moved on.

Now that sufficient time has passed, I think that list is going to be quite massive. Unfortunately, my Google-fu is pretty weak and I can’t seem to find it. If an eagle eyed user manages to find this thread, post in the comments below so I can link to it and hopefully expand my list here as well.

This list is drawn from recommendations by high level web developers who use these tools in their applications.

And as to my choices here, this list represents a superset of recommendations which flowed in after I asked some of the front end community to pitch in with the solutions they’re using. Some of the solutions below may handle dependency managements too, though most stick to simple asynchronous loading. Regardless of the extra niceties, each of the scripts below do one thing with aplomb — load up JavaScripts with minimal fuss.

So without further ado, and in no particular order:


HeadJS

Head JS loads scripts in parallel no matter how many of them and what the browser is. Load scripts like images. Use HTML5 and CSS3 safely. Target CSS for different screens, paths, states and browsers. Make it the only script in your HEAD.

Author: Tero Piirainen

Project URL: Here

Size: 6.3 KB

Related links:


LabJS

LABjs (Loading And Blocking JavaScript) is an all-purpose, on-demand JavaScript loader, capable of loading any JavaScript resource, from any location, into any page, at any time. You can easily specify which scripts have execution order dependencies and LABjs will ensure proper execution order. This makes LABjs safe to use for virtually any JavaScript resource, whether you control/host it or not, and whether it is standalone or part of a larger dependency tree of resources.

Author: Kyle Simpson

Project URL: Here

Size: 4.7 KB

Related links:


RequireJS

RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.

Author: James Burke

Project URL: Here

Size: 13 KB

Related links:


ControlJS

ControlJS is a JavaScript module that handles both inline scripts and external scripts, delays script execution until after the page has rendered, allows for scripts to be downloaded, not executed and integrates with simple changes to HTML and no code changes

Author: Steve Souders

Project URL: Here

Size: 3.6 KB

Related links:


StealJS

The StealJS project is a collection of command and client based JavaScript utilities that make building, packaging, sharing and consuming JavaScript applications easy. Includes modules for dependency management, JS compression, cleaning and logging.

Author: Brian Moschel

Project URL: Here

Size: 11.4 KB

Related links:


yepnope

yepnope is an asynchronous conditional resource loader that’s super-fast, and allows you to load only the scripts that your users need. It works with both JavaScript and CSS and has a full test suite in QUnit that you can run in your set of supported browsers to make sure it works.

Author: Alex Sexton and Ralph Holzmann

Project URL: Here

Size: 3.4 KB

Related links:


PINF JS Loader

The loader allows for bootstrapping a consistent and state-of-the-art CommonJS environment for any supported platform (on server & in browser) and thus is ideally suited to be used as the target for the commonjs command and the development of cross-platform JavaScript applications and libraries.

Author: Christoph Dorn

Project URL: Here

Size: 22 KB

Related links:


JSLoad

JSLoad is a Javascript file loader that we wrote for Instructables. You give it a set of dependencies and groupings, and it loads the files you need, when your executing code needs them. The real usefulness of JSLoad comes with its ability to group dependencies using tags.

Author: Eric Nguyen

Project URL: Here

Size: 9.8 KB

Related links:


JsDefer

JsDefer features parallel/serial loading based on definitions, dependency, and wrapped versus unwrapped, and whether dependencies are defined in separate def file or in script itself and integration with Deferred (as in jQuery 1.5) enables or simplifies many use-case scenarios among many others.

Author: Boris Moore

Project URL: Here

Size: 4.7 KB

Related links:


JSL (JavaScript Loader)

JSL features on-demand loading, is browser cacheable, dynamic asynchronous JavaScript loading, lazy loading and duplicate source prevention among a ton of other features.

Author: Andres Vidal

Project URL: Here

Size: 2.1 KB

Related links:


YUI 3 Get

The Get Utility provides a mechanism for attaching script and css resources — including cross-domain resources — to the DOM after the page has loaded.

Author: Adam Moore

Project URL: Here

Size: 17.9 KB

Related links:


DominateJS

DominateJS allows you to asynchronously load all your JavaScript, and defer sequential execution until the page loads. DominateJS aims to be a cross-browser and 100% document.write-safe library! This is a heavily modified (and powerful!) evolution of ControlJS.

Author: Chris Joel & Jason Benterou

Project URL: Here

Size: 48 KB


Load.js

load.js is a micro JS lazy-loader. Built on top of chain.js, it allows you to lazy load your JS scripts sequentially or in parallel and handle complex dependency chains.

Author: Chris O’Hara

Project URL: Here

Size: 2 KB

Related links:


BravoJS

BravoJS is an implementation of a proposed draft for CommonJS Modules/2.0

Author: Wes Garland

Project URL: Here

Size: 10.7 KB


Bootstrap

Bootstrap is a small library for dynamically loading JavaScript files.
It’s primary use case is for using in your JS code to load JS files only when they are used.

Author: Scott Koon

Project URL: Here

Size: 1.3 KB


LazyLoad

LazyLoad is a tiny (only 904 bytes minified and gzipped), dependency-free JavaScript utility that makes it super easy to load external JavaScript and CSS files on demand.

Whenever possible, LazyLoad will automatically load resources in parallel while ensuring execution order when you specify an array of URLs to load. In browsers that don’t preserve the execution order of asynchronously-loaded scripts, LazyLoad will safely load the scripts sequentially.

Author: Ryan Grove

Project URL: Here

Size: 1.6 KB


curl.js

curl.js is a small, but very fast AMD-compliant asynchronous loader. Current size: 4.5KB (2.1KB gzipped) using Google’s Closure Compiler.

If you’d like to use curl.js for non-AMD modules (ordinary javascript files), you’ll want to use the version with the js! plugin built in. You may also want to build-in the domReady module. The combined curl+js+domReady loader is still only 6.1KB (2.7KB gzipped).

Author: John Hann

Project URL: Here

Size: 5 KB


$script.js

$script.js is an asynchronous JavaScript loader and dependency manager with an astonishingly impressive lightweight footprint. Like many other script loaders, $script.js allows you to load script resources on-demand from any URL and not block other resources from loading, like CSS and images.

Author: Dustin Diaz

Project URL: Here

Size: 1.4 KB


NBL.js

NBL.js is a tiny script that will make your HTML pages load faster by loading all your JavaScript files asynchronously (in parallel) with the rest of your page. Normally if you include two or three scripts in your page, the browser will wait for them to be executed before your page is shown.

Author: Berklee

Project URL: Here

Size: 971 B

Related links:


That’s a Wrap!

While each of the tools listed above handle script loading in slightly unique ways, be sure to perform your tests when deciding which is the right one for you.

As I mentioned earlier, if you think a loader should be here but isn’t, drop us a line below and we’ll update the roundup accordingly.

 
 

jStat – A Statistical Library With JavaScript

10 Apr

jStat is a JavaScript library which enables you to perform advanced statistical operations without the need of a dedicated statistical language.

Simply, it focuses on being a real JavaScript-based alternative for languages like R and MATLAB.

The library is standalone, however, for the plotting functionality, it requires jQuery, jQuery UI and jQuery-flot plugin.

jStat

Special Downloads:
Ajaxed Add-To-Basket Scenarios With jQuery And PHP
Free Admin Template For Web Applications
jQuery Dynamic Drag’n Drop
ScheduledTweets

Advertisements:
Professional XHTML Admin Template ($15 Discount With The Code: WRD.)
Psd to Xhtml
SSLmatic – Cheap SSL Certificates (from $19.99/year)

 
 

This Time, You’ll Learn Node.js

08 Apr

Node.js is an amazing new technology, but, unless you’re specifically a JavaScript developer, the process of becoming acquainted with it can quickly become a bit overwhelming. But that’s why we’re here! If you want to really learn how to use Node.js, this set of articles and screencasts will do the trick.


An Introduction to Node.js


Press the HD button for a clearer picture.
View more Nettuts+ screencasts on YouTube.

Screencast Transcript

Hi guys, my name is Christopher Roach, and I’ll be your guide throughout this series of screencasts on Node.js. In this series we’ll be using Node to create a simple blog engine, like the one made famous in the popular Ruby on Rails introductory video. The goal of this series is to give you, the viewer, a real feel for how Node works so that, even when working with any of the popular web development frameworks out there, such as Express or Getty, you’ll feel comfortable enough with the inner workings of Node to be able to drop down into its source and make changes to suit your needs as necessary.


Installation

Before we get into some of the details of what Node is and why you’d want to use it, I’d like to go ahead and get us started with the installation of Node, since, though super easy, it can take some time.

Node is still very young, and is in active development, so it’s best to install from the source.

Node is still very young, and is in active development, so it’s best to install from the source. That said, Node has very few dependencies, and so compilation is nowhere near as complicated as other projects you may have fought with in the past. To get the code, visit the Node.js website . If you scroll down the page to the download section, you’ll find a couple of choices. If you have Git installed, you can do a clone of the repository and install from there. Otherwise, there’s a link to a tarball that you can download instead. In this video, I’ll keep things simple, and install from the tarball.

While this is downloading, now is a good time to mention that efforts are ongoing to provide a port of Node for Windows, and there are instructions for installing on Windows for Cygwin or MinGW. I believe there are even some binary packages out there that you can install from, but at the time of this writing, it’s primary environment is Unix and Linux based platforms. If you’re on a Windows machine, you can click on the link for build instructions and follow the set of instructions there for a Windows installation or you can install a version of Linux, such as Ubuntu, and install Node there.

When it’s finished download, simply untar and unzip the package with tar -xvf and cd into the directory it created. First we need to do a ./configure, then make, and finally make install. That’s going to take a little time to build, so I’ll let that run in the background and take this opportunity to talk a bit more about Node, and why it’s causing such a stir in the web development community.


Introduction to Node

Node is JavaScript on the server.

So, if this article and video is your first introduction to Node, you’re probably wondering just what it is and what makes it worth learning when there are already so many other web development frameworks out there to choose from. Well, for starters, one reason you should care is that Node is JavaScript on the server, and let’s face it, if you work on the web, love it or hate it, you’re going to have to work with JavaScript at some point. Using JavaScript as your backend language as well as for the client-side means a whole lot less context switching for your brain.

Oh, I know what you’re thinking: “so Node is JavaScript on the server, well that’s great, but there’ve been other JavaScript on the server attempts in the past that have basically just fizzled.”

What makes Node any different from the rest?

Well, the short answer is: Node is server-side JavaScript finally done right. Where other attempts have basically been ports of traditional MVC web frameworks to the JavaScript language, Node is something entirely different. According to its website, Node is evented I/O for V8 JavaScript, but what exactly does that mean? Let’s start with V8.

V8 is Google’s super fast JavaScript implementation that’s used in their Chrome browser.

Through some really ingenious application of “Just in Time” compilation, V8 is able to achieve speeds for JavaScript that make users of other dynamic languages, such as Python and Ruby, green with envy. Take a look at some of the benchmarks and I believe you’ll be amazed. V8 JavaScript is up there with many JVM-based languages such as Clojure and Java and compiled languages, such as Go in many cases.

JavaScript’s ability to pass around closures makes event-based programming dead simple.

The other key phrase in that statement is evented I/O. This one is the biggie. When it comes to creating a web server you basically have two choices to make when dealing with multiple concurrent connection requests. The first, which is the more traditional route taken by web servers such as Apache, is to use threads to handle incoming connection requests. The other method, the one taken by Node and some extremely fast modern servers such as Nginx and Thin, is to use a single non-blocking thread with an event loop. This is where the decision to use JavaScript really shines, since JavaScript was designed to be used in a single threaded event loop-based environment: the browser. JavaScript’s ability to pass around closures makes event-based programming dead simple. You basically just call a function to perform some type of I/O and pass it a callback function and JavaScript automatically creates a closure, making sure that the correct state is preserved even after the calling function has long since gone out of scope. But this is all just technical jargon and I’m sure you’re dying to see some code in action. I’m going to fast forward a bit to the end of this install, so we can start playing around with our brand new, freshly minted copy of Node.


Confirming the Installation

So, it looks like my build has finally finished; I want to quickly check and make sure that everything went well with the install. To do so, simply run node --version from the command line, and you should see some indication that you’re running the latest version of Node which, at this time, is version 0.4.5. If you see a version print out then you can rest assured that everything went swimmingly and you’re ready to write your first Node app. So, let’s cd back into our home directory and create a new folder to hold all of our work during the course of this series of screencasts. Here I’m simply going to call mine ‘blog‘ and let’s cd into that to get started.


Node – The Server Framework

Unlike other frameworks, Node is not strictly for web development. In fact, you can think of Node as a framework for server development of any kind. With Node you can build an IRC server, a chat server, or, as we’ll see in this set of tutorials, an http server. So since we can’t have an introductory tutorial without the obligatory ‘Hello World‘ application, we’ll begin with that.


Hello World

Let’s create a new file called app.js. Now Node comes with a handfull of libraries to make the development of event-based servers easy. To use one of the available libraries, you simply include its module using the require function. The require function will return an object representing the module that you pass into it and you can capture that object in a variable. This effectively creates a namespace for the functionality of any required module. For the creation of an HTTP server, Node provides the http library. So let’s go ahead and require that now and assign the returned object to the http variable.

Next, we’ll need to actually create our server. The http library provides a function called createServer that takes a callback function and returns a new server object.

The callback function is what Node calls a listener function and it is called by the server whenever a new request comes in.

Whenever an HTTP request is made, the listener function will be called and objects representing the HTTP request and response will be passed into the function. We can then use the response object inside of our listener function to send a response back to the browser. To do so, we’ll first need to write the appropriate HTTP headers, so let’s call the writeHead function on our response object.

The writeHead function takes a couple of arguments. The first is an integer value representing the status code of the request which for us will be 200, in other words, OK. The second value is an object containing all of the response headers that we’d like to set. In this example, we’ll simply be setting the Content-type to ‘text/plain’ to send back plain text.

Once we’ve set the headers, we can send the data. To do that, you’ll call the write function and pass in the data that you wish to send. Here, let’s call the write function on our response object and pass in the string “Hello World“.

To actually send the response, we need to signal to the server that we’re done writing the body of our response; we can do that by calling response.end. The end function also allows us to pass in data as well, so we can shorten up our server code by getting rid of the call to the write function that we made earlier and instead passing in the string “Hello World” to the end function, like so.

Now that we’ve created our server, we need to set it up to listen for new requests. That’s easy enough to do: call the listen function on our server object and pass in a port number for it to listen on; in this case I’ll be using port 8000. The listen function also takes an optional second parameter which is the hostname URL, but since we’re just running this locally, we can safely skip that parameter for now.

Finally, let’s print out a message to let us know that our server is running and on what port it’s listening for new requests. You can do that by calling console.log, just like we would in the browser, and passing in the string “Listening on http://127.0.0.1:8000“. There we go, now let’s run our app by calling node and passing to it the name of the file we want it to execute.


THE REPL

Before we bring this first article and video in the series to a close, let’s flip back over to the terminal and quickly take a look at Node’s REPL.

A REPL, for those unfamiliar with the acronym, stands for Read-Eval-Print-Loop which is nothing more than a simple program that accepts commands, evaluates them, and prints their results.

It’s essentially an interactive prompt that allows you to do pretty much anything that you can do with regular Node, but without all the overhead of creating a separate file, and it’s great for experimentation, so let’s play around a bit with the REPL and learn a bit more about Node.

We’ll first need to stop our server application by hitting Ctrl-C. Then run node again, this time, however, without a filename. Running node without any arguments will bring up the REPL, as we can see here by the change in the prompt. The REPL is very simple: basically you can write JavaScript code and see the evaluation of that code. Despite its simplicity, though, the REPL does have few commands that can come in handy and you can get a look at each of these by calling the .help command at the prompt. Here (refer to screencast) we see a list of four commands, the first of which is the .break command. If you are writing some code that spans several lines and you find that you’ve made some type of mistake, and need to break out for whatever reason, the .break command can be used to do so. Let’s try it out now…

I’m going to create a function here and I’ll just call it foo and open the function body and then hit enter. Notice that, on the next line, rather than seeing the typical greater than symbol, we now see a set of three dots, or an ellipsis. This is Node’s way of indicating to us that we have not yet finished the command on the previous line and that Node is still expecting more from us before it evaluates the code that we’ve typed in. So, let’s go ahead and add a line of code now: we’ll do console.log and we’ll print out the name of the function. Let’s now hit enter, and, again, notice that the ellipsis character is being displayed once more. Node is still expecting us to finish the function at some point. Now let’s assume that I’ve made a mistake and I just want to get back to a normal prompt. If, I continue to hit enter, Node continues displaying the ellipsis character. But, if I call the .break command, Node will break us out of the current command and takes us back to the normal prompt.

Next, we have the .clear command. This one will clear our current context. So if you’ve cluttered up the environment with the creation of several variables and functions and you want a clean slate, simply run the .clear command and Voila, everything magically disappears.

.exit and .help

Finally, there’s the .exit and .help commands. The .help command is fairly obvious, since it’s the command we used to see the list of commands in the first place. The .exit command is equally obvious: you essentially just call it to exit the REPL, like so.

So, that pretty much covers all of the functionality that the REPL provides outside of the evaluation of the code you enter. But before we leave the REPL completely, I’d like to take this opportunity to discuss some differences and similarities between JavaScript in the browser and Node’s flavor of JavaScript. So let’s run Node again and jump back into the REPL.

The first difference between client-side JavaScript and Node is that, in the browser, any function or variable created outside of a function or object is bound to the global scope and available everywhere. In Node though, this is not true. Every file, and even the REPL, has its own module level scope to which all global declarations belong. We’ll see this put to use later in the series when we discuss modules and create a few of our own. But for now, you can see the actual module object for the REPL by typing module at the prompt. Notice that there is a prompt attribute buried a few levels deep in our module object? This controls the prompt that we see when in the REPL. Let’s just change that to something slightly different and see what happens. There now, we have a brand new prompt.

Another difference between Node JavaScript and browser JavaScript is that in the browser, you have a global window object that essentially ties you to the browser environment.

In Node, there is no browser, and, hence, no such thing as a window object. Node does however have a counterpart that hooks you into the operating environment that is the process object which we can see by simply typing process into the REPL. Here you’ll find several useful functions and information such as the list of environment variables.

One similarity that is important to mention here is the setTimeout function. If you’re familiar with client-side JavaScript, you’ve no doubt used this function a time or two. It basically let’s you setup a function to be called at a later time. Let’s go ahead and try that out now.

> function sayHello(seconds) {
...	console.log('Hello ');
...	  setTimeout(function() {
...     console.log('World');
...   }, seconds * 1000);
... }

This will create a function that when called, prints out the string ‘Hello’ and then a few seconds later prints the string ‘World’. Let’s execute the function now to see it in action.

> sayHello(2);

There are a couple of important ideas to take notice of here. First, Ryan Dahl, the creator of Node, has done his best to make the environment as familiar as possible to anyone with client-side JavaScript experience. So the use of names such as setTimeout and setInterval rather than sleep and repeat, for example, was a conscious decision to make the server-side environment match, wherever it makes sense, the browser environment.

The second concept that I want you to be aware of is the really important one. Notice that, when we call sayHello, right after printing the first string, control is immediately given back to the REPL. In the time between when the first string is printed and the callback function executed, you can continue to do anything you want at the REPL’s prompt. This is due to the event-based nature of Node. In Node, it’s near impossible to call any function that blocks for any reason and this holds true for the setTimeout function. Lets call our sayHello function again, however, this time let’s pass in a slightly longer timeout interval to give us enough time to play around a bit and prove our point. I believe 10 seconds should do the trick.

There we see the first string. Let’s go ahead and run some code of our own, how about 2 + 2. Great, we see that the answer is 4 and… there’s our second string being printed out now.


Conclusion

So that brings us to the close of the first episode in this series. I hope this has been a fairly informative introduction to Node for you, and I hope I’ve done a decent enough job of explaining why it’s so exciting, what it has to offer, and just how fun and simple it is to use. In the next episode, we’ll actually start writing some of the code for our blog engine; so I hope you’ll all join me again when things get a bit more hands on. See you then!

 
 

33 Developers you MUST Subscribe to as a JavaScript Junkie

09 Feb

As JavaScript developers, we have quite crazy requirements. The playing field is in a state of constant flux and one of the best ways to keep up is interacting with other developers and reading their code. Blogs, such as the one you’re reading, are a perfect amalgamation of these two activities.

Today, I’d like to bring your attention to a number of blogs written by pretty well versed developers, focusing on JavaScript development, that you owe yourselves to bookmark.


A Quick Word on my Choices

Even though these blogs aren’t updated often, in fact a lot of them get updated maybe thrice a year, the content they do have are worth their weight in, well, smartly written JavaScript. The developers below vary from wildly popular to almost obscure but they have one thing in common — their passion for JavaScript.

I’ve limited myself to a cliff notes version of each dev to keep it short. Don’t loiter around — click on those links and get reading!


John Resig

Developer Image

Douglas Crockford

Developer Image

Dean Edwards

Developer Image

Nicholas C. Zakas

Developer Image

Dustin Diaz

Developer Image

Brendan Eich

Developer Image
  • Find his musings on JavaScript at his blog.
  • Inventor of the JavaScript language.
  • Works at Mozilla.
  • Remember to check out his podcast, as well.
  • Tweets at @BrendanEich

David Flanagan

Developer Image

Thomas Fuchs

Developer Image

Paul Irish

Developer Image

Yehuda Katz

Developer Image

Juriy Zaytsev

Developer Image

Peter van der Zee

Developer Image
  • Find his musings on JavaScript at his blog.
  • Creator of the JS1K competition
  • Tweets at @kuvos

Stoyan Stefanov

Developer Image

Dmitry Baranovskiy

Developer Image

Lucas Smith

Developer Image
  • Find his musings on JavaScript at his blog.
  • YUI team member
  • Tweets at @ls_n

Ben Alman

Developer Image
  • Find his musings on JavaScript at his blog.
  • Contributor to the jQuery and Modernizr projects.
  • Creator of so many jQuery plugins that we’re ethically obligated to use the word buttload.
  • Tweets at @cowboy

Rey Bango

Developer Image
  • Find his musings on JavaScript at his blog.
  • jQuery team member.
  • Works at Microsoft.
  • Tweets at @reybango

Remy Sharp

Developer Image

Cody Lindley

Developer Image

James Padolsey

Developer Image

Oliver Steele

Developer Image

Ben Cherry

Developer Image
  • Find his musings on JavaScript at his blog.
  • Works at Twitter.
  • Github repos here.
  • Tweets at @bcherry

Michael Bolin

Developer Image

James Coglan

Developer Image

Angus Croll

Developer Image
  • Find his musings on JavaScript at his blog.
  • Works at Twitter.
  • Tweets at @angusTweets

John-David Dalton

Developer Image
  • Find his musings on JavaScript at his blog.
  • Author of the FuseJS library.
  • Github repos here.
  • Tweets at @jdalton

Andrea Giammarchi

Developer Image

Peter Michaux

Developer Image
  • Find his musings on JavaScript at his blog.
  • Dude is a darn enigma, wrapped in a riddle, shrouded in mystery. The articles are pretty much one of the best you’ll get to read so don’t miss out.

Christian Heilmann

Developer Image

Dion Almaer

Developer Image

Rebecca Murphey

Developer Image

David Walsh

Developer Image

Addy Osmani

Developer Image
  • Find his musings on JavaScript at his blog.
  • Member of the jQuery team [bug triage and API docs].
  • Tweets at @addyosmani

That’s a Wrap!

I’m sure a lot of you are frothing at the mouth by this list not including someone. Fret not! Chime in below and I’ll make sure to keep this list periodically updated.

 
 

Quick Tip: Display Elements Sequentially with jQuery

13 Dec

In this video quick tip, I’ll teach you how to add a bit of flair to your page, by displaying a set of elements sequentially. While there are numerous ways to accomplish this task, today, we’ll review one technique that uses recursive functions.

// Wrapping, self invoking function prevents globals
(function() {
   // Hide the elements initially
   var lis = $('li').hide();

   // When some anchor tag is clicked. (Being super generic here)
   $('a').click(function() {
      var i = 0;

      // FadeIn each list item over 200 ms, and,
      // when finished, recursively call displayImages.
      // When eq(i) refers to an element that does not exist,
      // jQuery will return an empty object, and not continue
      // to fadeIn.
      (function displayImages() {
         lis.eq(i++).fadeIn(200, displayImages);
      })();
   });
})();

Conclusion

What makes this usage effective is the fact that, when lis.eq(i) refers to an element that doesn’t exist in the wrapped set, an empty jQuery object will be returned. When this happens, the subsequent methods in the chain (fadeIn) will never be called.

 
 

Instant Previews: Under the hood

15 Nov

If you’ve used Google Search recently, you may have noticed a new feature that we’re calling Instant Previews. By clicking on the (sprited) magnifying glass icon next to a search result you see a preview of that page, often with the relevant content highlighted. Once activated, you can mouse over the rest of the results and quickly (instantly!) see previews of those search results, too.

Adding this feature to Google Search involved a lot of client-side Javascript. Being Google, we had to make sure we could deliver this feature without slowing down the page. We know our users want their results fast. So we thought we’d share some techniques involved in making this new feature fast.

JavaScript compilation

This is nothing new for Google Search: all our Javascript is compiled to make it as small as possible. We use the open-sourced Closure Compiler. In addition to minimizing the Javascript code, it also re-writes expressions, reuses variables, and prunes out code that is not being used. The Javascript on the search results page is deferred, and also cached very aggressively on the client side so that it’s not downloaded more than once per version.

On-demand JSONP

When you activate Instant Previews, the result previews are requested by your web browser. There are several ways to fetch the data we need using Javascript. The most popular techniques are XmlHttpRequest (XHR) and JSONP. XHR generally gives you better control and error-handling, but it has two drawbacks: browsers caching tends to be less reliable, and only same-origin requests are permitted (this is starting to change with modern browsers and cross-origin resource sharing, though). With JSONP, on the other hand, the requested script returns the desired data as a JSON object wrapped in a Javascript callback function, which in our case looks something like

google.vs.r({"dim":[302,585],"url":"http://example.com",ssegs:[...]}).

Although error handling with JSONP is a bit harder to do compared to XHR (not all browsers support onerror events), JSONP can be cached aggressively by the browser, and is not subject to same-origin restrictions. This last point is important for Instant Previews because web browsers restrict the number of concurrent requests that they send to any one host. Using a different host for the preview requests means that we don’t block other requests in the page.

There are a couple of tricks when using JSONP that are worth noting:

  • If you insert the script tag directly, e.g. using document.createElement, some browsers will show the page as still “loading” until all script requests are finished. To avoid that, make your DOM call to insert the script tag inside a window.setTimeout call.
  • After your requests come back and your callbacks are done, it’s a good idea to set your script src to null, and remove the tag. On some browsers, allowing too many script tags to accumulate over time may slow everything down.

Data URIs

At this point you are probably curious as to what we’re returning in our JSONP calls, and in particular, why we are using JSON and not just plain images. Perhaps you even used Firebug or your browser’s Developer Tools to examine the Instant Previews requests. If so, you will have noticed that we send back the image data as sets of data URIs. Data URIs are base64 encodings of image data, that modern browsers (IE8+, Chrome, Safari, Firefox, Opera, etc) can use to display images, instead of loading them from a server as usual.

To show previews, we need the image, and the relevant content of the page for the particular query, with bounding boxes that we draw on top of the image to show where that content appears on the page. If we used static images, we’d need to make one request for the content and one request for the image; using JSONP with data URIs, we make just one request. Data URIs are limited to 32K on IE8, so we send “slices” that are all under that limit, and then use Javascript to generate the necessary image tags to display them. And even though base64 encoding adds about 33% to the size of the image, our tests showed that gzip-compressed data URIs are comparable in size to the original JPEGs.

We use caching throughout our implementation, but it’s important to not forget about client-side caching as well. By using JSONP and data URIs, we limit the number of requests made, and also make sure that the browser will cache the data, so that if you refresh a page or redo a query, you should get the previews, well... instantly!

By Matías Pelenur, Instant Previews team
 
 

Microsoft Gets a Clue, Adopts jQuery

29 Sep

Could Microsoft be learning the way things work on the web? That big software company in Redmond will include JavaScript framework jQuery in its development environment. At the same time, Nokia announced that it will use jQuery for its mobile-browser development. That’s two more big companies to join Google, Amazon and thousands of other sites using jQuery.

Microsoft has long struggled to keep up with advances in JavaScript. In July the company announced an Ajax roadmap, which looked like Microsoft was going to eventually re-create all the features already in popular frameworks. Instead, Microsoft is going to incorporate someone else’s code, and it’s open source code at that.

How’s this for cool–Intellisense support for jQuery in ASP.NET:
Intellisense code includes jQuery

This is a great move by Microsoft to avoid creating its own jQuery-like framework. The company that seems to always require others to change is adapting to the way things already are on the web. It couldn’t have made a better choice in jQuery, which is a fast, nimble framework, two adjectives not often used to describe anything related to MS web development.

Scott Hanselman has a good overview of how jQuery/ASP.NET code looks. If you aren’t a .NET developer, but you’d like to use jQuery, check out my jQuery tutorial.

[Screenshot by Scott Hanselman]

See also:

 
Comments Off on Microsoft Gets a Clue, Adopts jQuery

Posted in Uncategorized

 

10 Smart Javascript Techniques to Improve Your UI

16 Sep

Javascript can add a lot of special effects that can really improve the user's experience. Here are 10 simple and clever Javascript techniques that add an extra dose of usability to any webpage.

 
Comments Off on 10 Smart Javascript Techniques to Improve Your UI

Posted in Uncategorized