TAG | Javascript
The more I play around with Node.js, the more I love server-side JavaScript. Once you get over the weirdness of writing JavaScript outside of the browser, it feels very natural. And the bonus is that it is blazing fast.
Also, as I’ve been playing around with YQL (Yahoo Query Language) more lately, I realized I wanted to be able to access YQL data from within my Node app. So, I created a node-yql module.
Now you can do something like…
YQL.get("SELECT * FROM weather.forecast WHERE location=90066", function(response) { var location = response.query.results.channel.location, condition = response.query.results.channel.item.condition; sys.puts("The current temperature in " + location.city + " is " + condition.temp + " degrees"); }); // Output: The current temperature in Los Angeles is 57 degrees
Ajaxian had a story yesterday about a brand-new JavaScript playground called jsFiddle. A write and execute web-based JavaScript IDE is nothing new, but this is much, much more than that.
The real power of jsFiddle is that you have the option to include any of the most popular JS libraries, including; Mootools, jQuery, Prototype, YUI2.8, YUI3, Glow, Vanilla, Dojo, Processing.js, & ExtJS. This feature gives anyone the ability to try out any of these libraries without going through the task of downloading, extracting, and coded up some examples. With a few mouse-clicks you can view example snippets from any of the major JS libraries, and start editing them to see how they work.
As if that wasn’t enough, jsFiddle also includes social features that give you the ability to write a snippet, save it, and share the URL. As I was hanging out in various JavaScript IRC chatrooms tonight, I continually found myself using jsFiddle to code up snippets to answer questions. In the past, everyone would always just use Pastebin.com, but that lacks any interactive features. Now you can use jsFiddle as a replacement to Pastebin for any JS, HTML, or CSS snippets and the user will have the ability to actually edit, execute, and view the output.
As icing on the cake, you can take your snippets, copy the embed code, and paste them anywhere. Here’s a snippet that I was able to code up in about 15 minutes (writing this blog post took longer than that!) to demonstrate the power of YUI3, YQL, and the Twitter API. In this iframe, you’ll find all the JS, CSS, and HTML you need to create a simple little Twitter widget.
In all, this is an amazing product that I’ll likely find myself using on a daily basis.
I just finished watching Part 1 of Douglas Crockford’s ongoing lecture series on JavaScript, and it’s fascinating stuff. A must watch for any programmer. Even if you don’t code in JS, it’s worth watching simply because this first part is all about the history of programming. (video of talk is below)
As web developers, we spend anywhere from a little bit of our time to the majority of it coding in JavaScript, but few know the history behind the language. I’m not talking about just reading the Wikipedia article and knowing that it was created by Brenden Eich at Netscape in ‘95, I’m talking about the history of where the ideas behind the language came from and everything that influenced it. Like most every language, JavaScript’s syntax and style didn’t appear out of nowhere, it was influenced by a number of different languages, and those influencers were in turn also influenced by a slew of languages.
It’s easy for those of us that started programming with C (or anything after) to just look at it as the “Alpha” language and ignore everything that happened before it, but that’s missing a lot of really important history, that we, as professionals, should know. It’s like a politician in the United States just ignoring everything that happened before 1776. Learn from the mistakes of the past and spot the trends going forward and pave the best path. Crockford shows us snippets of languages that were created in the 60’s and 70′, dissects them, and explains why certain people thought they were good ideas at the time. It’s amazing to think that there was a time before modules or functions, or before we had figured out the best way to format a for loop. The history of programming languages is littered with a ton of bad ideas, but occasional brilliant ideas. Those brilliant ideas are what get refined, and lay the foundation in the next generation of languages.
Finally, one concept he goes back to over and over that I found really interesting is that programmers are a very stubborn breed. We all know this. There’s little point to all our flame wars on which language or framework is better, and most of it comes from either insecurity or ignorance. He says it takes a long time for us to evolve, and he’s right. It’s not because new ideas aren’t coming along all the time, but it’s because the adoption of new ideas only take place at each generation shift, when the “old” thinkers get replaced those with few preconceived notions. The world didn’t wake up one day and realize that GOTO statements were bad, it’s that those who supported GOTO and argued for it for a decade finally retired. Out with the old, in with the new. That’s evolution.
Anyways, I could go on and on about all the “Ah hah!” moments in this talk, but you really need to watch it for yourself. I’ll probably chime in again after part 2, which I’m probably going to watch right now. I’m excited. It’s like a sequel. “Ooo! What happens now?!”
Also, here’s the “Mother of all Demos” video he mentions about halfway through.
If you are doing some more advanced JavaScript applications, you’ll likely run into the problem at one point or another when you need to dynamically generate the name of a function you wish to call. This is the equivalent of PHP’s call_user_func().
Here’s how you can do it.
// Define some vars var foo = "hello"; var bar = "world"; var function_name = "say_" + foo + bar; // Since its name is being dynamically generated, always ensure your function actually exists if (typeof(window[function_name]) === "function") { window[function_name](" World!"); } else { throw("Error. Function " + function_name + " does not exist."); } function say_helloworld(the_word) { alert("Hello " + the_word); } // Browser will alert "Hello World!"
When you think about it, it makes a lot of sense considering all global objects in JavaScript are actually properties of the “window” object. Take a look at this example to understand that concept a bit more.
var foo = "apple"; function foobar() { var foo = "orange"; alert(window["foo"]); // alerts "apple" alert(foo); // alerts "orange" alert(window["foobar"]); // alerts the foobar function } foobar();
Here’s another example of when using a string to call a function could come in handy. This time we’re calling the property of an object we’ve created.
function Person() { this.message = "Hello World!"; this.say_hello = function(to) { alert(this.message); } } var Derek = new Person(); function_name = "say_hello"; Derek[function_name]();
See how it looks pretty much the same as the method above using a global function?
Hope that shed some light on your problem.
As JavaScript becomes a more integral part to the core functionality of websites, ensuring that a user has a fresh copy of the latest code is as important as ever. Normally a browser will cache certain filetypes (CSS, JS, JPG, etc…) for an indefinite period of time. If the code within one of these cached files is updated, sometimes a browser will not know to reload that file. So, if those changes are important for the functionality of your website, your users may run into issues and not be able to use your site properly. Worse, they likely won’t have any idea what the issue is and will eventually give up and go elsewhere. But have no fear, there’s a solution to this problem… versioning your static files.
By “versioning” these files, I’m referring to changing their filenames from “my_styles.css” to “my_styles.version274.css” for example. The problem with that example is it relies on you renaming the file and updating your includes every time you make a change. That sounds like an nightmare, right? Luckily there’s a neat tactic you can you to make it appear to the browser to be a new file, but it will actually be the same file and will require no effort on your part. This variation of the versioning tactic is often referred to as “Auto-versioning”. Here’s an example…
First, we use the following rewrite rule in .htaccess:
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-s # Make the file doesn't actually exist RewriteRule ^(.*)\.[\d]+\.(css|js)$ $1.$2 [L] # Strip out the version number
Now, we write the following PHP fuction:
/** * Given a file, i.e. /css/base.css, replaces it with a string containing the * file's mtime, i.e. /css/base.1221534296.css. * * @param $file The file to be loaded. Must be an absolute path (i.e. * starting with slash). */ function auto_version($file) { if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file)) return $file; $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file); return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file); }
Now, wherever you include your CSS, change it from this:
<link rel="stylesheet" href="/css/base.css" type="text/css" />
To this:
<link rel="stylesheet" href="<?=auto_version('/css/base.css')?>" type="text/css" />And when rendered, will appear as:
<link rel="stylesheet" href="/css/base.1251992914.css" type="text/css" />
How does this work? Because that mod_rewrite rule above will strip out the timestamp, your server will deliver /css/base.css as the requested file. But to the user’s browser, it will appear as a different file whenever it is updated.
Neat!
Note: Some strategies to fix this caching issue is to append a version # onto the end of the css or JavaScript file with a querystring, such as:
<link rel="stylesheet" href="/css/base.css?version=1234" type="text/css" />
This method will actually prevent the file from being cached, period! This is bad. You want the benefits of caching. You don’t want to make your users pull down 100k of JavaScript & CSS files on every page load. More importantly, your servers could start to strain under the additional load.
Why is it not cached? See Section 13 from the HTTP Specification, in particular Section 13.9
13.9 Side Effects of GET and HEAD
Unless the origin server explicitly prohibits the caching of their responses, the application of GET and HEAD methods to any resources SHOULD NOT have side effects that would lead to erroneous behavior if these responses are taken from a cache. They MAY still have side effects, but a cache is not required to consider such side effects in its caching decisions. Caches are always expected to observe an origin server’s explicit restrictions on caching.
We note one exception to this rule: since some applications have traditionally used GETs and HEADs with query URLs (those containing a “?” in the rel_path part) to perform operations with significant side effects, caches MUST NOT treat responses to such URIs as fresh unless the server provides an explicit expiration time. This specifically means that responses from HTTP/1.0 servers for such URIs SHOULD NOT be taken from a cache. See section 9.1.1 for related information.
26
Tweenky, Zendcon, vacations, CCCKC, DotNext, etc…
0 Comments | Posted by Derek in Random, Technology, Web Development
Blogging is something that comes in waves for me, and once I get out of the habit, it is tough to get back into it. I enjoy it, but sometimes there’s just so much going on that it completely escapes me. The last few months have been one of those periods. So let’s start from the top…
I’ve been working on a new project recently. Tweenky is a micro blogging client I am developing that is mostly used with Twitter, but also supports Identi.ca, and hopefully more micro-blogging services soon. The concept behind it was the lack of any good web clients out there for Twitter, and especially ones that brought back the “track” feature that Twitter took away from us a few weeks back. It’s still very much a work in progress and I just have to find the time to work on some of the new features and further improve stability. I’m having a blast with pushing the boundaries of JavaScript and what it should/shouldn’t be used for. So, if you are a Twitter user, go check it out, and if it is still requiring an invite code, use “derekville”.
So I just returned from a convention out in Santa Clara called Zendcon. As a web developer, my primary language of choice is PHP, and Zend is the company puts most of the work into the PHP project, so this was kind of their little yearly shindig. It was 4 days of 1-2 hour training sessions on all topics related to PHP and web development. I saw some presentations from engineers and developers from companies such as IBM, Google, Mozilla, Digg, Yahoo, and tons more. I met a ton of really interesting people too and had a great time at Yahoo HQ for Hackday ‘08. (note to self: Don’t wear “Hackday ‘08″ shirt to airport, it leads to hacker questioning from TSA agents)
Vacation #1 was on the front & back end of the Zendcon trip as I had a few days before & after the conference to play around in San Francisco. It’s such a cool city and I had a blast driving around in the Pontiac G6 convertible I rented for the week. I’ve never had so much fun driving a car!
Vacation #2 is coming up next month with Katye & I flying up to Seattle where we’ll also head up to Vancouver & Victoria. I haven’t been to Seattle in about 10 years, so I’m really excited as I love that city. Everyone I’ve talked to raves about Vancouver too, so I’m pretty excited about my first trip north of the border.
If you are a web developer in the Kansas City area, you need to check out two emerging groups. The first being DotNext, a group in the KC area that gets together every month or so to give sessions on anything web development related. Last month was a series of presentations of Amazon Web Services. This month is going to be on various database related technologies. The second group is Cowtown Computer Congress who is setting up a hacker space in North Kansas City. For those not too familiar with what a “hacker space” is (myself included), it is a place for technologists to get together to work on various hardware & software projects, share costs on equipment, and actually socialize (something most geeks never do much of). So should be an awesome place to convene when it officially opens in the next couple months.
And finally, a new podcast from some rather influential people in the web development world has launched that I’d like to mention. Open Web Podcast was created by Google engineer Dion Almaer (of the Ajaxian podcast as well), Alex Russell of Dojo, and John Resig of Mozilla/jQuery. So if you are into web standards and JavaScript, definitely check it out.
Finally, I recently discovered the FX show “It’s Always Sunny in Philadelphia”. Hilarious! Check out all the episodes on Hulu.
Well, I finally got around to giving Ajax (Asynchronous JavaScript and XML) a whirl. I wasn’t trying to do anything spectacular, just something functional to wet my appetite. I started out just wanting to allow people to send me text messages via the side bar. I got it all set up using PHP in about 2 minutes, and I thought… “It works, but I hate reloading the page for something so simple.” And then Ajax popped in my head and thought it would be a great first script.
So off I went to grab the latest version of SAJAX (Simple Ajax), and boy were they right about the “simple” part. Within about 30 minutes, I had a functional script that you can now find on the side bar. Before you try it out, please use the demo page, as I don’t need everyone sending me text messages just to see how it works.
Next step, getting my responses to show up. =)
Edit: At first that last comment was a joke, but two hours later…, that was shockingly easy. I’d like to get it integrated into the side bar, but out of time tonight. I’ll post the code when I have a bit more time to work on it. So feel free to send a message or two, as I can respond rather easily. If you get annoying, I can turn it off via my cell phone too.

