Tag Archives: javascript

Twitter Web Intents

Twitter recently launched a new feature for integrating their service into your website. Web Intents automagically converts links to specific URLs into interactive dialogs, using the same widgets.js dependency as the retweet widget.

You can create links to retweet, reply to or favorite messages, as well as to follow or display a user.

As an example:

<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<a href="http://twitter.com/intent/retweet?tweet_id=53796378291355649">Retweet</a>

More fun things for developers and web designers to play with. And you can now get official logos and UI sprites as well.

Twitter Web Intents [Twitter Developers]

Google Rolling Out Asynchronous AdSense Ads

Remember when BuySellAds started using non-blocking JavaScript to load advertisements on publisher’s sites? It made a huge difference in the speed pages took to load, since the ads wouldn’t load until all of the important stuff was done.

Google is finally doing the same with AdSense, with new asynchronous ad-serving code that is currently being used to load ads quicker in Chrome, Firefox and Internet Explorer 8. (They plan to expand to support other browsers after they’ve ironed the kinks out of the new script.)

The old show_ads did lots of work: loading additional scripts, gathering information about the web page it was running on, and building the ad request to send back to Google. The new show_ads has a different job. It creates a friendly (same-origin) iframe on the web page, and starts the old script with a new name, show_ads_impl, running inside that iframe. The _impl does all the heavy lifting, and in the end the ads look exactly the same. But there’s a substantial speed advantage: many things happening inside an iframe don’t block the web browser’s other work.

Publishers don’t need to change anything; Google took care of everything on their end. Supposedly it should shave off about 12% of the time it takes for the page to load, since the ads won’t hold up the page while they load.

Evil JavaScript Trick: The History Nuker

Remember back in the bad old days of the internet, when pop-up ads and other annoyances were around every corner? Some sites, by some flawed logic, would decide that you didn’t really want to leave their website when you clicked the Back button and would attempt to disable it with JavaScript. The technique they would generally use was to use the “unload” event handler to fire a document.location change, bouncing you back to the same page you were trying to leave. This, of course, was easily defeated by hammering the Back button, as a quick double-press of the Back button could override the JavaScript.

Fortunately the days when people thought that to be an acceptable practice are over.

While reading about JavaScript “hashbang” URLs, I had a thought. An evil thought. You could build a better Back button-disabling script by using the same technique used to enable the back button in AJAX-heavy websites. (Take a look at Google Instant Search’s pagination, or Twitter, to see it in action.)

I thought, what if you looped around a large number of times, changing the URL fragment, until the back button became useless? Not only would it be a pain to click the Back button, say, 300 times, the browser starts to “forget” the previous pages after one or two hundred pages. (They stay in the history, but the Back button only remembers a few.)

So I made a quick proof-of-concept. I used setTimeout() instead of an ordinary for loop, so the browser doesn’t hang when you push a few hundred items onto the history stack and window.location.hash to change the URL fragment.

var theURL = document.URL;

i = 0;
nukeBackButton = setInterval("addAFragment()", 1);

function addAFragment() {
if (i > 300) {
 clearInterval (nukeBackButton);
}
window.location.hash = "#fragment" + i;
i++;
}

You can see it in action here. It works rather well, though of course tabbed browsing easily circumvents it. (Thankfully.)

Note: I do not advocate the use of this script, and anybody who does use it is a fiendish menace to the internet. This is to be used purely for academic purposes.

Eloquent JavaScript: A Modern Introduction to Programming

It’s amazing how much JavaScript has changed over the years. What was once mainly used for creating pop-up windows, rollover images and the like is now an integral part of the modern web, making web applications like GMail and Twitter possible. I first learned JavaScript from the old No Star Press title The Book of JavaScript, published back in 2000. As was typical back in those days, it began with a good into to variables, functions and loops, then taught you how to do common tricks like open new windows and manipulate HTML framesets.

For nostalgia’s sake, and because I enjoyed it’s older predecessor, I jumped at the chance to read No Starch’s fresh new book, Eloquent JavaScript: A Modern Introduction to Programming. Upon opening it for the first time, it was pleasant to see that No Starch uses the same characteristic typesetting and layout.

Marijn Haverbeke takes an unusual approach for a JavaScript book. Instead of focusing on scripting web pages, he teaches you how to program, and JavaScript just happens to be the language. The book, in addition to covering the usual “here’s how to do arrays and stuff,” features more advanced topics like recursion, object-oriented programming, modularity, and other interesting bits of programming theory. It’s examples are even more advanced than is normal, one chapter focusing on how to split input text into paragraphs and extract relevant data from the sentences.

The book also has a wonderful introduction, one that captures the spirit of programming quite well (besides making you feel like a “mighty wizard”).

To some of us, writing computer programs is a fascinating game. A program is a building of thought. It is costless to build, it is weightless, and it grows easily under our typing hands. If we are not careful, its size and complexity will grow out of control, confusing even the person who created it. This is the main problem of programming: keeping programs under control. When a program works, it is beautiful. The art of programming is the skill of controlling complexity. The great program is subdued, made simple in its complexity.

All in all, a JavaScript book and programming primer that stands apart from the rest. A good book for people who want to learn more than how to copy code snippets, and an interesting read more those who already know what they’re doing.

HTML5 Boilerplate

HTML5 Boilerplate is a default template that you can use as a starting point to build HTML5-ready web designs around. It has a few neat features, like:

  • Full cross-browser compatibility…even with IE6. It uses some scripts to add support to those uncool browsers. You can use the new HTML5 elements today. Even the video element.
  • @font-face
  • Server configuration templates (available for Apache, NGINX, and other servers) to add caching and compression.
  • Mobile optimizations
  • Print stylesheet
  • IE6 pngfix is included
  • Plenty of utility classes like .no-js and .clearfix

It’s definitely worth checking out for future reference. The reset stylesheet is fairly similar to the one I tend to use, and the HTML seems fairly well-optimized, with the scripts loading in the footer and everything.

The Pragmatic Guide to JavaScript

There are plenty of books that teach JavaScript from a basic introductory angle. The Pragmatic Guide to JavaScript is a bit different. It’s a lightweight guide (around 130 pages) for those of us who already know a programming language or two. Instead of covering boring stuff like variables and functions—let’s face it, they’re not all that different from language to language—it shows you some real-world use cases in convenient byte-size portions.

The book’s format is interesting. Each chapter is a two-page spread with the text on one side and code samples on the other. Each of the chapters deals with a single practical usage of JavaScript, such as:

  • Dynamically selecting methods and properties
  • Using the Module Pattern to prevent naming collisions
  • Optional function arguments
  • Dynamically styling content
  • Preloading images
  • Form validation and dynamic form fields
  • AJAX, JSON, JSON-P and cross-domain AJAX
  • An introduction to mashups

Another neat feature is the way it shows examples using straight JavaScript as well as with different frameworks.

Overall the book seems like a great way to dive right into JavaScript, providing you already have some scripting experience with another language. It was quite useful to me, as by grounding in JavaScript isn’t nearly as good as with PHP. I learned a few new tricks.

Speed Up Your Site With Head JS

Head JS is a 2.3 kilobyte script that makes it easy to asynchronously load your JavaScript files to prevent blocking. It allows the browser to load the web page separately from the scripts, so the rendering process isn’t held up by the download.

Non-blocking loading is the key to fast pages. Moreover Head JS loads scripts in parallel no matter how many of them and what the browser is. The speed difference can be dramatic especially on the initial page load when the scripts are not yet in cache. It’s your crucial first impression.

If you have a JavaScript-heavy website, it’s worth taking a look at. If you take a look at the demo pages they have set up, the page that uses Head JS to load the scripts definitely displays much faster.

Head JS :: The only script in your HEAD [Head JS]

Generate QR Codes On-the-Fly With the Google Chart API

You’ve probably seen a QR code before, even if you didn’t know what it was at the time. It’s a little square matrix barcode that can be read by either a specialized scanner or a cellphone with the right software. UPS puts QR codes on their packages for tracking purposes, and many Android phones come with QR readers preinstalled for easily sharing links to apps.

A QR code can contain any sort of textual information, which will be decoded by a QR reader. A web address, a simple message, a phone number, etc.. A good QR reader should figure out what the decrypted data is and act upon it accordingly. If it’s a web address, it will display the web page. If it’s a phone number, it should display the number and offer to call it.

Users of the iPhone or fourth-generation iPod Touch can use a free app like QR Reader to scan QR codes.

What can you use a QR code for? There are plenty of possible applications. Magazines could print QR codes that let you quickly jump to a web page. (Anyone remember the CueCat?) Advertisements could have QR codes that offer more information. You could put a QR on your business card. Want to move a web page you’re reading from your computer to your phone? Create a quick QR matrix and scan it right off the screen!

Now for the fun part… How do you make your own QR codes?

Continue reading →

JSONView: View JSON Data in Firefox

JSON is a popular way to format AJAX responses, as it’s more compact than XML and essentially a JavaScript object, but it can be a real pain to work with due to uncooperative browsers. It’s easy enough to view XML in a web browser, which is good for testing, but JSON responses cause a download prompt to open. This makes it harder to verify that an AJAX request is working properly.

Fortunately, a clever developer has built a Firefox extension to solve this problem. JSONView renders a plain-text representation of the JSON object, complete with indentation and color-coding whenever you access a URL that outputs JSON data. For example, the Twitter API. If you click this link in Firefox, you will be prompted to download the file. With JSONView installed, you would see output from the following image.

If you do much JavaScript work, be sure to install JSONView. It will save you some headaches when you have AJAX requests that aren’t working quite right.

MediaElement.js — HTML5 Video Player With Flash Backup

Many modern web browsers have early support for the <video> and <audio> elements in the HTML5 spec. Unfortunately, their implementation varies depending on the ideals of the various browser developers. Safari expects video to be encoded in the high-quality H.264 codec, other browsers prefer Ogg Theora. Google is trying to push their own freely-licensed VP8 codec, which Mozilla is showing signs of adopting. Then there’s Internet Explorer, which doesn’t support the <video> element at all.

Thankfully, there’s a way to fairly easily support everything. You can offer HTML5 video in one or more formats and fall back on Silverlight or Flash if necessary.

MediaElement.js allows you to do that with a little bit of jQuery voodoo. After including all of the required files, you can serve-up an H.264 video for Safari and iPhone/iPad users like so:

<video src="myfile.mp4" type="video/mp4" width="640" height="360"></video>
<script>
jQuery(document).ready(function($) {
$('video').mediaelementplayer();
});
</script>

There is also a way to specify more than one video type in the <video> element, if you have re-encoded it into more than one codec:

<video width="640" height="360">
<source src="myfile.mp4" type="video/mp4" >
<source src="myfile.ogg" type="video/ogg" >
<source src="myfile.webm" type="video/webm" >
</video>

You will want to check it out if you’re interested in cross-browser compatible web video.