Posts tagged JavaScript
TweeterFall – Web Workers
1
How often have you seen this dialog, or something similar – telling you that some scripts on a page are taking too long while your browser has become completely unresponsive. Because JavaScript runs in the same thread as the rest of the browser UI, we’re often faced with the challenge of being unable to run any complex or long running JavaScript without the fear of blocking the browser. That’s where web workers come in.
Web Workers are part of the HTML5 specification and allow you to run scripts in the background, independently of the main browser thread. This means that you can do complex calculations or run scripts that may take a while to run without yielding to keep the page responsive. The W3C spec has some great examples of use cases and other helpful descriptions that are worth reading for deeper details. It also notes that workers are relatively heavy weight and are not intended to be used in large numbers.
In order to to maintain thread safety, workers run in an effective sandbox, which means they don’t have access to the DOM or many other components. To get information back and forth between the worker and the main application, we need to use the postMessage method and listen for message events.
In TweeterFall, we used a worker thread poll Twitter for new tweets and then we ‘pushed’ those new tweets to the main thread. Let’s have a look how we used workers.
Starting & Stopping the Worker
We only ever have one working running in our application, and to maintain an easy handle to it, we defined it’s variable in the global scope. We then had two methods that would handle how the worker would behave – startWorker() and stopWorker(). The startWorker() method takes a parameter that provides information about the username or list that we want to pull tweets from, how often we should poll Twitter and the ID of the last tweet we saw.
var myWorker;
function startWorker(settings) {
settings.cmd = "start";
settings.lastTweetID = lastTweetID();
console.log("WebWorker: Starting", settings);
myWorker = new Worker("scripts/worker.js");
myWorker.addEventListener("message", newTweetHandler, false);
myWorker.postMessage(settings);
}
function stopWorker() {
if (myWorker != undefined) {
console.log("WebWorker: Terminating");
myWorker.terminate();
myWorker = null;
}
}
In our startWorker() thread, we create the new worker with myWorker = new Worker("scripts/worker.js");, and then add an event listener and listen for any messages that the worker wants to pass back to us – this is the only way we’re going to be able to communicate to the worker because it’s working off in it’s own little isolated world. At this point, the worker exists, and if it wants to tell us anything, we’re ready to listen, but now we need to tell it to do something, which is the myWorker.postMessage(settings);.
Stopping our worker is pretty similar, we check to make sure that we have a valid object, and as long as we do, .terminate() will immediately close the worker without giving it an opportunity to shut down properly or clean up after itself. This works in our case because we don’t have anything in memory and we’re not doing any calculations of any kind. If you may need to save state or want to clean up after yourself, the better way to shut down would be to send a stop message via .postMessage() and within your worker thread, shut down gracefully by calling self.close(); after completing any clean up.
The Worker Thread
Inside our worker thread, we need to set up an event listener to listen for messages from our parent thread and any other code that we want to execute.
self.addEventListener('message', function(e) {
var data = e.data;
switch (data.cmd) {
case 'start':
self.postMessage("Worker: Starting");
setConfig(data);
readTweets();
break;
case 'stop':
self.postMessage("Worker: Stopping");
self.close();
break;
default:
self.postMessage("Worker: Error - Unknown Command");
};
}, false);
Our event listener listens for messages from the parent and will start or stop the worker as necessary. When we get the start command, we parse the settings data (setConfig), and then start reading tweets (readTweets()). For sake of readability, I’ll skip the code we used for setConfig(), but it’s easy enough to find if you want it.
function getURL() {
var sinceID = "";
if (parseInt(lastKnownTweetID, 10) > 0) {
sinceID = "&since_id=" + lastKnownTweetID;
}
if (typeof userList === 'undefined') {
return 'http://twitter.com/statuses/user_timeline/' + twitterUser
+ '.json?count=' + tweetCount+ '&callback=processTweets' + sinceID;
} else {
//For a list
return 'http://api.twitter.com/1/' + twitterUser + '/lists/' +
userList + '/statuses.json?callback=processTweets' + sinceID;
}
}
function readTweets() {
try {
var url = getURL();
self.postMessage("Worker: Attempting To Read Tweets From - " + url);
importScripts(url);
}
catch (e) {
self.postMessage("Worker: Error - " + e.message);
setTimeout(readTweets, 120000);
}
}
readTweets() is the function that does the dirty work, making a JSONP call to Twitter that requests the latest tweets. We encapsulated the URL generation into it’s own method so that we could use it even if we weren’t using workers. Because we don’t have access to the DOM, we can’t just insert a <script> block, so after getting the URL, we call importScripts(url);, which makes an synchronous call and injects the result into the worker. If we run into any problems, like over capacity, not being able to reach Twitter or anything else, it’s caught in the catch block, and we wait two minutes before trying again. Here’s the JSONP call we make http://api.twitter.com/1/petele/lists/chromedevrel-11/statuses.json?callBack=processTweets.
The request we sent to Twitter includes ?callback=processTweets in the query string which will cause processTweets() to be executed once we’ve pulled the new tweets from Twitter.
function processTweets(data) {
var len = data.length;
for (var i = 0; i < len; i++) {
if (data[i].id_str >= lastKnownTweetID) {
lastKnownTweetID = data[i].id_str;
}
}
returnTweets(data);
}
function returnTweets(data) {
if (data.length > 0) {
self.postMessage("Worker: New Tweets - " + data.length);
self.postMessage(data);
} else {
self.postMessage("Worker: New Tweets - 0");
}
setTimeout(readTweets, updateDelay);
}
processTweets() enumerates all of the tweets we got back to find the most recent tweet ID. That way, when we ask Twitter again later for tweets, we’re only asking for the ones that we haven’t seen. Once we’ve done that, we call returnTweets() to push the new tweets back to the application. We could have merged processTweets() and returnTweets(), and I don’t remember why I decided to do it as two separate methods. Once we’re returned the tweets via returnTweets() we use setTimeout() to call readTweets() again.
A couple of quick tips
A couple things to remember about web workers, no DOM access means that you can’t manipulate the DOM, so that means that if you want to create new UI components in threads, you can, but you need to do it in the thread, and then pass that back to the main application via postMessage(). Unfortunately, it also means that jQuery doesn’t work in threads, so generating those UI components becomes a little more complex. I’ve heard rumors of a worker safe jQuery library, but haven’t seen it yet. Hopefully!
The other good thing to know is that you can debug works in the Chrome Developer Tools by clicking on the Scripts tab, and scrolling down in the column on the right to Workers and clicking on the debug checkbox.
Summary
I found using workers to be really easy, and a good way of handling this. There are plenty of other good ways to use workers – and it gives us some pretty good power to be able to push complex work down to the client. Especially as browsers JavaScript engines are getting faster and faster.
Additional Resources
Tips & Tricks: Cheat Sheets For Web People
2I have a set of blogs that I read every day, some are really technical, and I learn lots, and others are more inspirational, they show me the cool stuff that we as web designers and web developers can build.
I’ll admit that one of the blogs I read has the educational value of something you’d pick up at a grocery store check out, the pictures are really pretty, and it’s good inspiration, but I’d never actually walk out of the store with it. Well today, they posted an article that changed my mind. Almost! One of today’s posts was a collection of cheat sheets for web designers and developers, and I wanted to share my favorites.
HTML4 and HTML5 Cheat Sheets
HTML5 Visual Cheat Sheet from http://woorkup.com/
I think came in as my favorite and prettiest cheat sheet. It prints on an 11×17 piece of paper, and is a great reference for all of the HTML4 and HTML5 tags that you’ll ever need to reference. It nicely includes the attributes that you can set, what version of the HTML spec they’re from and lots more useful information.
HTML5 Reference Guide from http://veign.com/
The Veign folks go into a lot more detail on their cheat sheet, or more accurately, cheat sheets because this guy is 4 pages long. One of the things I like about this one was that it goes in to much further depth about the attributes, supported HTML versions (indicating elements that aren’t supported in HTML5 with a highlight), and a very brief description of the element.
HTML Character Entity Reference from http://addedbytes.com/
I’ve often found myself forgetting what the special character sequence is to get a particular character to show up, or I’ll be looking for a character to use in my breadcrumb navigation – this cheat sheet solves that and lists all of the characters and their sequence to get exactly what you want!
Canvas Cheat Sheet from http://blog.nihilogic.dk
Canvas is one of those things that’s super new to a lot of folks, so having a handy cheat sheet is really useful! It’s not going to be super-useful for beginners since it’s basically just the API reference, but once you have a pretty good handle on Canvas, this will be a great desk reference until it gets cemented in your brain.
CSS2 and CSS3 Cheat Sheets
CSS2 Reference from http://veign.com
Those folks over at Veign are pretty good at putting together a reference sheet, maybe not as pretty as some of the other ones, but just as functional and makes my life easier, so I’m not complaining! Their CSS2 reference is great and provides all the detail you’ll need if you need to look something up quickly!
CSS3 Reference from http://veign.com
The CSS3 reference isn’t quite as awesome as the HTML5 reference, because they don’t tell you what properties are CSS3 vs CSS2, so if you’re having to code for multiple browsers like most folks, you may accidentally add something and then scratch your head as to why it’s not working in an older browser.
Other Useful Cheat Sheets
JavaScript Cheat Sheet from http://addedbytes.com
For whatever reason, JavaScript and I don’t get along, I think it’s because I like strongly typed languages that tell me if I’ve done something wrong before it gets there. If you’re building websites and not using a tool that doesn’t have intellisense, then having a cheat sheet like this would be super valuable. All the APIs you’ll need, right at your fingertips!
SEO Cheat Sheet from http://www.seomoz.org
A week or so ago, I posted my tips and tricks for ensuring your site was best optimized to make it into search engines efficiently. Here’s another great easy to follow cheat sheet that will help you make the best of the time and resources that you have on getting your site optimized. It’s a great resource to look over and share with co-workers or friends when they ask why you’re doing something!
Summary
There you go, those are the quick reference guides that are now printed and sitting on my bulletin board beside my desk at work! Hopefully you’ll find a good nugget or two in there as well! If you’ve got other good references or cheat sheets, be sure to share them with me!
Web Site Performance Resources
0At TechEd last week, I presented a session that covered 20 Tips and Tricks for Writing Fast Web Applications. A couple of folks asked for more resources and where they could find more info, and I figured I’d share some of it here more publically.
I’d highly recommend checking out Steve Souders’ two books:
In the coming days/weeks, I’ll get some additional details posted about the 20 tips and tricks that I talked about, and how you can make sure you’re using them on your site!
Internet Explorer Developer Tools
5One the the coolest features of Internet Explorer 8 that most developers don’t know about are the build in developer tools. Think Firebug, except for Internet Explorer, and built by the IE Team, so you don’t have to download anything, install it, or enable it. Heck, my Mom could bring up the developer tools if she really wanted! Over the next week or so, I’m going to do a short series on the Internet Explorer Developer Tools and what you can do with them. Since Internet Explorer 9 is still in the “Platform Preview”, I’m going to focus on Internet Explorer 8, though there are some cool new IE9 tools, I’ll save those for another day.
Starting the Developer Tools
There are two ways you can open the IE Developer Tools, you can either hit F12, or under the Tools menu icon, you can choose “Developer Tools”. Both of these will open the Developer Tools, which you can either run in a separate window, or docked to the bottom of your browser window as I’ve shown below.

When the Developer Tools open, there are four main tabs that provide the major functionality of the tools
HTML Tab
This tab allows you to see and edit in real time the HTML and applied styles that make up your page as seen by the Internet Explorer DOM. From here you can move through the DOM either via the tree view on the bottom left, or you can click on the little mouse pointer icon, and grab individual elements. When you do that, IE automatically takes you to the element you’ve selected. On the left side of the HTML panel, is another set of tabs, that show the Style and inheritance information for the CSS that’s being applied, an ability to Trace Styles, so you can see what particular style is being applied, and why. The Layout tab is particularly useful if you’re forgetful like me and mix up margin and padding (for years, I’ve not been able to keep it straight, and every time I think I’m remembering it right, I goof it up again). Finally the Attributes tab shows the attributes that are on that element.
The CSS Tab
Shows you all of the styles that are being pulled down for your site, how they cascade against one another and is useful to view and turn off styles individually or at the entire style level. Like the HTML tab, you can edit your styles in real time to see how changing properties affects the page. So if you’re not sure why something isn’t being styled right, this is a great place to look.
The Script Tab
Like any good development tools, debugging is a vital component of understanding why something isn’t working, or why you’re getting that a 3 instead of a 2. The Internet Explorer 8 developer tools let you do everything that you’d expect in a full-fledge debugger (it’s almost as powerful as the debugging tools in VS2010 – not quite, but pretty good). Like the HTML tab, there are several tabs on the right side of this window. There’s the Console tab, so you can output to the console window if you’ve added debugging code to your scripts. The Break Points tab, to help you be able to apply break points and debug into your code on specific lines. There’s also the Local and Watched Variables tab so you can see what’s happening to your variables as your applications is running. And finally the Call Stack tab to dig into the call stack.
The Profiler Tab
This is the one that I think is probably the coolest feature of the Internet Explorer 8 Developer Tools, and that’s the built in code profiler. Want to know what’s happening, what functions are being called, why things are taking longer than you expect, or not getting called, the Profile is your guide to what’s going on. Once you turn the Profiler on, you can run your code and IE will keep track of the number of times every method is called the length of time spend in that method (Exclusive Time), the length of time spend in that method and any methods called by that method (Inclusive Time), as well as where that method is.
Other Useful Developer Tool Features
There’s a couple other things that I want to highlight in this Internet Explorer Developer Tools introduction, that I think are really useful when I’m working on building a new site, or editing an existing one.
Browser Mode and Document Mode
Internet Explorer 8 shipped with two rendering engines, the Internet Explorer 7 rendering engine, and the Internet Explorer 8 rendering engine. By default, as long as you’ve include the right DOCTYPE switch, Internet Explorer 8 will use the Internet Explorer 8 rendering engine. But you can’t always guarantee your users are going to be using IE8, and you want to see how your site will look with the IE7 rendering engine.

Document Mode
Document Mode allows you to manually choose which rendering engine you want IE to render the page with; choosing the Internet Explorer 8 Standards mode uses the IE8 rendering engine, Internet Explorer 7 Standards Mode uses the IE7 rendering engine, or Quirks Mode uses the quirky, IE5.5 rendering engine. Changing the Document Mode does NOT change the user agent string that is sent to the server and is primarily used for testing and seeing how your site will look in IE7.
Browser Mode
Browser Mode changes both the Document Mode, and the User Agent string, which allows Internet Explorer 8 to lie about who it says it is.
- “Internet Explorer 8” uses the IE8 rendering engine and the UA string tells the server that the browser is IE8 by including the “MSIE 8.0” and “Trident/4.0” tokens in the User Agent String.
- ”Internet Explorer 8 Compatibility Mode” uses the IE7 rendering engine and the UA string tells the server that it’s IE7, but if you know better, it’s really IE8. It does this by sending the “MSIE 7.0” token along with the “Trident/4.0” token. That way, if the server is looking for “MSIE 7.0” and you get the expected IE7 behavior.
- ”Internet Explorer 7” uses the IE7 rendering engine and the UA string tells the server that the browser is IE7, it doesn’t include the “Trident/4.0” token, only the “MSIE 7.0”.
If you want to see what your browser is reporting for it’s user agent string, check out http://petelepage.com/samples/uastring.aspx. Then open the Developer Tools and try changing the Browser Mode and Document Mode to see how the page renders in different ways.
Color Picker
Ever wonder what color is on another site, and don’t want to dig into their CSS to find it, or don’t remember what color you picked, the color picker is a little eye dropper tool that lets you click on a particular part of the page and it gives you the HEX color value, so you can just plug it right in where you need it. You can find the Color Picker under the Tools menu!
More To Come!
In my future posts, I’ll dive deeper into each of the above features, and how you can use them to debug your websites!
20 Tips and Tricks For Writing Fast Web Applications
4I’m about 30 minutes from walking on stage to present my last session here at TechEd 2010 in New Orleans and I wanted to share this presentation early, just in case the session room fills up and folks can’t make it in or for those of you who weren’t able to make it. If you’re a TechEd attendee, the slides are up on the Schedule Builder, otherwise, you can find my deck here [8meg PPTX].
The Internet Explorer engineering team spends a lot of time working to understand what developers and doing when building their websites, where the bottle necks are (both in the browser and in the code that developers write). With all of the information that they gathered, they built set of 20 tips and tricks that will help your site run faster, and more efficiently. While the research they did used Internet Explorer as the base, almost all of these tips and tricks apply to all browsers.
Jason Weber presented these tips and tricks at MIX2010 this year – the session web page is at http://live.visitmix.com/MIX10/Sessions/CL29 and you can also download the slides, or the video in MP4, Windows Media Format or High Quality Windows Media Format. It runs about 80 minutes and should be required watching for every developer out there I think. I know I learned a few things and I think my site breaks some of the best practices that I’ve got listed below! (I guess I’ve got some work to do!
)
Without any further ado, I present to you…
20 Tips & Tricks To Improve Your Website Performance
- Ensure server side compression is enabled on “text” like files
- Use conditional requests
- Provide cacheable content
- Minify your JavaScript
- Don’t scale images (I’m really guilty of this one)
- Use image sprites
- Link JavaScript at the bottom of your file, and avoid inline JavaScript
- Add the “defer” tag when you have to link to JavaScript at the top of your page
- Link Style Sheets at the top of your page
- Avoid using @import
- Minimize Walking Look Up Chain
- Cache Function Pointers
- Use the Native JSON object
- Remove duplicate scripts
- Minimize DOM interactions
- Use efficient DOM Methods
- Use querySelectorAll for groups
- Only send required styles
- Simplify your selectors
- Minimize page layouts
PS: If you want a little laugh, go to the TechEd site, and look at my bio – it wasn’t quite supposed to read like that ![]()
[UPDATED 6/10/10 1:25pm PST] Fixed the link to the slides, sorry about that!
Browser Speed: It’s Not All About JavaScript
2On Tuesday, I presented my IE9: A Lap Around for Developers session here at TechEd and it went really well, it was a lot of fun, and the “slide” deck that I presented worked well! As it turns out, Joab Jackson, a reporter for the IDG News Service was in the audience and wrote a really great article that ran on PC World about how browser speed isn’t just dependant on JavaScript, but is affected by all parts of the browser!
http://www.pcworld.com/article/198396/microsoft_browser_speed_not_all_about_javascript.html
I’ll be posting my slides later this afternoon – just want to finish my last presentation of TechEd!



