All posts tagged ‘JavaScript’

File Under: JavaScript

A Rose by Any Other Name Might Smell as Sweet, But it Would Probably Be Larger

It may have started as a lark, but the annual JS1K contest has long since ceased to be a joke. This year’s contest is already in full swing and notable for a spectacular 3-D drawing of a rose rendered using less than 1,024 bytes of JavaScript.

The JS1K contest seeks the web’s best JavaScript creations, with one small catch — the code used must be less than 1k. It might sound insane considering that some JavaScript frameworks — just the frameworks! — are over 100k, but since it began several years ago, JS1K’s experiments have never failed to impress.

One of this year’s most jaw-dropping efforts to date is developer Román Cortés 3-D rendering of a rose. Relying on Monte Carlo methods to keep the code size down, Cortés’ code draws a very nicely shaded 3-D rose for the love-themed 2012 edition of JS1K. You can check out the live demo on the JS1K website.

One word of warning: Part of what makes Cortés’ rose so small is that much of the heavy lifting is handed off to the processor. The demo code brought my CPU use over 100 percent and kept it pegged there the entire time it was open in Safari. Firefox and Chrome both managed to keep the number down to roughly 93 percent, but suffice it to say that a procedurally generated 3-D rose will tax your CPU.

To see how Cortés created the code behind the rose, be sure to visit his blog which offers a very thorough tutorial explaining how and why the code works. There’s also a great write-up on Cortés’ previous JS1K effort, a 3-D Christmas tree. Also be sure to check out the other submissions to this year’s JS1K contest on the JS1K website.

If you’ve got some impressive but terribly small bit of JavaScript code up your sleeve, fear not; the JS1K contest will continue accepting submissions through Wednesday, March 14, 2012. Details on the rules and submission process can be found on the JS1K website.

Google Throws New ‘Dart’ Programming Language at the Web

It’s not every day that someone tries to add a new programming language to the web. There’s a good reason for that. The great trinity of web development — HTML, CSS and JavaScript — while not perfect, has proved itself highly flexible and capable of adapting as it evolves, which, in the end, might be more important than perfection.

But, regardless of how well those three have served the web thus far, they are not enough for Google, which is hoping the web will now embrace Dart, Google’s brand-new programming language for “structured web programming.”

The first hint of Dart surfaced about a month ago when an internal Google memo was leaked onto the web (the memo itself dates from 2010). In it Google claims that “JavaScript has fundamental flaws that cannot be fixed merely by evolving the language.” The answer, for Google, was to go off and create its own homebrewed solution.

That solution is Dart, a “class-based optionally typed programming language for building web applications.”

Lars Bak, a software engineer working on Dart, says the language is designed to work with every thing from “a one-person project without much structure to a large-scale project needing formal types in the code to state programmer intent.”

In other words, Dart is aiming to be a one-size-fits-all solution for writing apps on the web. Dart has been built from the ground up with this goal in mind. Indeed Dart offers some interesting tools, including optional types and the ability to declare private methods via an underscore. Unfortunately for Dart, a couple of novelties don’t seem to be winning over programmers. The Hacker News discussion thread on Dart is full of rather barbed critiques with hardly a supportive voice to be heard.

Dart on the web

Appealing to programmers is only half of what Dart needs to succeed; it also has to work well on the open web. For that Google has two solutions.

The first and ideal solution will be to execute Dart code in a browser-native virtual machine (very similar to how JavaScript is handled today). Of course that means the rest of the browser makers need to join Google in supporting Dart. Because that isn’t likely to happen any time soon, nor will it ever happen for legacy web browsers, Google has a fallback plan — a compiler that translates Dart code to JavaScript.

While the JavaScript compiler solution will mean slower web apps, it also means that Dart apps would always be able to run, regardless of the browser in question. That’s good for older browsers, but it also raises some questions about where Google plans to go with Dart.

Essentially, Google has set up a two-tier system for running Dart in the browser, and that is where Dart might run afoul of the open web.

Prior Dart Art

How Standards Proliferate by XKCD

The leaked Google memo that appeared on the web last month created a tempest in the web standards community teacup. The idea that Google had a secret project designed “to replace JavaScript as the lingua franca of web development” did not sit well with those who support open web standards.

The company appears to have backed off that stance somewhat for the official release. In fact, Google hardly mentions JavaScript in its Dart announcement and Lars Bak tells CNet that Dart is “not going to replace JavaScript…. JavaScript is a cornerstone of the web today, and it will continue to be for a long, long time.”

That message may be too little, too late. Publicly, Google may now be pushing the message that Dart is complimentary to JavaScript, but the blunter language and goals outlined in the leaked memo are already out there, fresh in developers’ minds. That, combined with Google’s less than stellar track record with its “open” projects may make it difficult for Dart to find supporters.

While Dart is open source and available for anyone to use, Google does not have a strong record of fostering open projects; that is, projects where the community can not just download and compile code (Andy Rubin’s “definition of open“) but can actually have a hand in creating features and guiding the direction of the project.

Until the latter component is well established, don’t expect other browser makers to adopt Dart. So long as Google controls the strings it’s unlikely its arch rivals like Microsoft and Apple will support Dart.

Without that support, Dart won’t be running in a virtual machine; instead it will fall back to running as JavaScript. That effectively means that, while Dart will run in any browser, it will likely have subpar performance in any browser lacking the virtual machine.

What standards proponents fear is a web where only Google’s Chrome browser ever fully supports Dart. That would mean that, while Dart apps would work everywhere, they’d be significantly faster in Chrome. That would send the web back to the bad old days of “works best in Internet Explorer” websites, only this time around it would be “works best in Google Chrome.”

Future Dart

It’s possible that Google will use Dart to finally create a true community-driven project. The company has already said it plans to eventually submit Dart for standardization, which would certainly help.

It’s too early to write off Dart, but it’s also too early to say it will be anything more than a novelty Google uses in its own apps (like WebP or even SPDY). Even if Dart can convince both developers and browser makers to jump on board, don’t look for Dart to become the “lingua franca of web development” any time soon.

See Also:

File Under: JavaScript, Programming

Scratchpad Puts a JavaScript Editor Inside Firefox

Firefox 6 is set to make its move from beta to final release this week, and we’ll look at the latest version once it’s official, but in the mean time the Mozilla Devtools blog has posted details on a new feature for JavaScript developers: Scratchpad.

If you’re a JavaScript developer you probably use tools like web console or Firebug or some combination of both to test and debug your code. Both are handy, but both are primarily line by line tools, what do you do when you want to test massive scripts?

Firefox’s new Scratchpad is different from Firefox’s other JavaScript dev tools in that it is just, as the Mozilla Blog puts it, "a text editor that knows how to run JavaScript." Scratchpad gets its own window and makes life much easier when you’ve got a long script to debug.

To use Scratchpad, head to Tools >> Web Developer >> Scratchpad, which will bring up a new, smaller window with a rudimentary text editor in it. Write your code, select some (or all) of it and then select one of three options from the Execute menu: Run, Inspect or Display. Scratchpad can also save your scripts or even load external JavaScript files.

Scratchpad is never going to replace your favorite text editor, but it just might make it a bit easier to test long scripts in the browser. For more info on everything Scratchpad can do, head over to the Mozilla Devtools blog.

See Also:

Review: Hype Animates the Web, No Flash Necessary

To create animations using web standards like HTML5, CSS 3 and JavaScript requires writing code. That’s fine for programmers who love nothing more than the blank space of a new document in their favorite text editor, but it’s a problem for designers accustomed to the visual, drag-and-drop workflow of animation apps like Flash. There’s nothing quite like Adobe’s Flash application for designers who want to stick with web standards.

Hype is hoping to change that. The new Mac OS X application uses many of the familiar interface elements that Adobe Flash offers — timelines, keyframes and drag-and-drop editing — but generates web standards output consisting of HTML, CSS and JavaScript. In short, Hype hopes to be to standards-based animation what the Flash app is to creating Flash movies.

While the initial release of Hype is impressive, it’s far from a Flash replacement. Perhaps more disappointing is that animations created with Hype suffer some of the same drawbacks you’ll encounter when using Flash.

The Good

For those with a background in Flash, the Hype learning curve is very short. Hype’s menu layout and palette structures are different, but the basic elements are essentially the same. To use Hype you drag objects — images, videos, vector art, etc — onto the stage and then you animate them by creating keyframes. One thing that’s different from Flash is Hype’s very handy “record” feature. To animate an element, just get everything where you want it for the first frame, add a new keyframe and then click record. Everything you do after that is recorded and translated into CSS and JavaScript-based animation.

To create a more complete movie-like animation Hype uses scenes, which break up your content and allow you to create transitions. For example, to create a slideshow, just drag your images into Hype and then create a new scene for each image. Add some transitions and you’re on your way. (That’s not the only way to create a slideshow, but it’s one of the simplest.)

Hype doesn’t offer everything you’ll find in Flash. Most notably there is no concept of MovieClips — self-contained movies within movies. There’s also no equivalent to Flash’s customizable tweens and advanced filters for blending objects.

Hype does offers plenty of canned elements, like buttons, boxes, and text boxes, to speed up simple tasks like adding text and other elements to your animations. To add elements to your page you just head to the Insert menu, select what you want and then you can style it with the properties palette just like you would any other element in Hype.

Hype's Flash-like IDE makes animating easy

Hype is simple enough to use that I was able to download a copy, watch the intro movie and five minutes later I generated the simple animation at the bottom of this post. Naturally to create something more interesting and useful will take you a bit longer, but it’s nothing compared to writing out the CSS and scripts by hand.

While Hype is primarily a visual editor, there are options to access properties like an element’s innerHTML and the Identity palette allows you to customize element IDs so you can target that element from other scripts. This is particularly handy if you want to create some custom CSS on top of what Hype generates.

The Bad

Hype, despite what its marketing materials claim, does not generate HTML5. It generates good old (standards compliant) HTML 4, CSS and JavaScript. That shouldn’t detract from from what Hype is capable of, but it’s disappointing to see the amount of HTML5, ahem, hype, surrounding Hype. Hype doesn’t even use canvas elements (animations are wrapped in div tags), nor does it use any of the new APIs (like say History or Web Workers).

Perhaps most disappointingly Hype doesn’t use the HTML5 History API. Because of the way Hype documents are embedded in a page, like Flash animations, Hype breaks the browser’s back button. What’s even more disappointing about Hype breaking the back button is that it’s not necessary. If Hype supported the History API, Hype documents could easily update the URL and not break one of the most fundamental elements of the web (see Mark Pilgrim’s excellent write up in the History API for more details on how to use it).

In some use cases that won’t matter, but if you’re thinking Hype would make a great slideshow creator, well, keep in mind that no one will ever be able to link to your individual photos without some extra effort on your part. Similarly, any transitions that happen in any Hype animation won’t be accessible via the back button.

Hype does offer an embedded editor so you can hook up the JavaScript yourself and take advantage of the History API, but then you’re back to writing code yourself.

Hype also makes some assumptions about your site structure when it generates HTML and JS. If you’ve got FTP access to your server then there’s nothing to worry about. But to embed my simple Hype animation in this post I had to change quite a few file references in the code. Hype assumes that all the resources it needs are in the resources folder it creates. Since I don’t have FTP access to this domain there is no way to get that folder on the server. Instead I uploaded the three required files through WordPress and then had to edit the generated Hype code to add the correct file paths. It wasn’t all that hard, but it did mean digging into the code, which at least partially defeats the purpose of Hype.

Another things to keep in mind is that Hype is heavily geared toward the WebKit rendering engine. While most of the effects work just fine in other standards compliant browsers, there are a few things that only work in WebKit. Where possible Hype falls back to pure JavaScript (for example in browsers that don’t understand CSS 3). Fortunately the Hype export function will warn you about any browser incompatibilities when you publish.

Conclusion

Despite some publishing hiccups and a few missing features, Hype is still one of the easiest ways I’ve seen to create Flash-free web animations. It’s like having most of what’s good about Adobe’s Flash app, without the downside of publishing to the Flash file format. Sadly Hype still falls prey to some of Flash’s weaknesses, but this is a 1.0 release and no doubt Hype will improve as time goes on.

Hype is currently available for $30 in the Mac app store. If you’ve been wanting to transition from Flash-based animations to web standards, but haven’t wanted to wade through the complexities of JavaScript and CSS 3, Hype is the droids you’ve been looking for. Just bear in mind that it has a few shortcomings of its own.

Hype Example

Here’s a very simple example of an animation created with Hype. Use the WebKit Inspector or Firebug to see how it works.

File Under: HTML5, JavaScript

How to Use HTML5′s Local Storage Tools Today

Cookies have long been the primary way to save information to a user’s browser. Whether it’s login info, preference settings or generic form data, most web developers turn to browser cookies. But HTML5 offers a new way to store data in the browser — the client-side storage APIs.

To take advantage of client-side storage you just need to write a bit of JavaScript. One of the best things about localStorage is how easy it is to use. For example, say you want to store a user’s favorite website. Here’s the JavaScript code you’d need to do that:

localStorage.setItem('favoriteSite','Webmonkey.com');

Then to access the stored info you just call it by name:

localStorage.getItem('favoriteSite');

Unfortunately, like much of HTML5, older browsers don’t know what to do with localStorage calls in your code. That does not mean, however, that you can’t use localStorage today, it just means you need a good fallback option for browsers that aren’t up to handling HTML5.

Developer Louis Remi has a post over on the Mozilla Hacks blog outlining how you can get started with localStorage and handle older browsers at the same time. The trick is to use Store.js as a fallback shim for older browsers.

Remi has already turned his experiment into a JQuery plugin, Persival, which allows you to create a web form capable of withstanding accidental tab closings or browser crashes.

If you’re just getting started with localStorage, be sure to check out Christian Heilmann’s write up over at Smashing Magazine which makes a good primer on both the why and how of HTML5′s localStorage API.

Of course localStorage has a dark side as well. It’s one of several tricks behind the rather scary “evercookie,” so, as with all things powerful, use responsibly.

Storage container photo by Louis Vest/Flickr/CC

See Also:

File Under: CSS, HTML5, Web Standards

A Guide to HTML5 Features You Can’t Detect

What language does that browser speak?

What language does that browser speak?

Web developers looking to play with the new features in HTML5, CSS 3 and other NEWT tools are still struggling with incomplete and inconsistent browser support. While HTML5 and its siblings are far from perfect (and complete), that doesn’t mean you can’t use them; it just means using them is a little more complicated since you need to detect the current browser’s level of support and then adjust accordingly.

One of the easiest ways to detect the current web browser’s level of HTML5 support is the Modernizr JavaScript library. We’ve covered Modernizr several times in the past and it’s a great addition to any HTML5 toolkit.

But sadly, not everything can be detected with JavaScript. If you’ve ever bashed your head against the keyboard trying to figure out why something wasn’t being detected, Modernizr has a new wiki page for you: The Undetectables.

The page lists a number of features that simply can’t be detected using general feature tests. Instead, these features can be found by either user agent sniffing (which leads to heartache and doom), browser inferences or as the wiki puts it “simply providing the same (slow) fix to everyone.”

In some cases there are workarounds, like the great keypress JavaScript effort from Google , which fixes a number of erratic, inconsistant keyboard behavior quirks in today’s browsers. However, in many cases you’re probably better off avoiding the undetectable features until browsers catch up.

If your code has been behaving strangely, despite your best efforts to detect a browser’s features, save yourself some hair pulling and head over the new Modernizr page to see if perhaps the problem is on the list of things that can’t be detected. If you discover other problems trying to sniff a browser’s capabilities, be sure to let the Modernizr devs know about it.

See Also:

Building Better HTML5 Games With Canvas

Canvas drawing speeds in Firefox 4 beta 7

The Canvas element is one of the most exciting parts of HTML5. It gives web developers a blank slate to create animations, games or even interactive video elements, all of which previously required plugins like Flash or Silverlight.

Canvas is not, however, a panacea — just because you can does not mean you should. Canvas-based animations can slow down pages, send your PC’s fan into overdrive and produce stuttering, frame-dropping ugliness. The stunning HTML5 experiment The Wilderness Downtown, was indeed very cool, but it also nearly crippled even the newest PC hardware.

As with most programming, the trick to using HTML5′s canvas element is knowing how to optimize your code so it works within the limits of today’s browsers.

We’ve looked at some tips and tricks for working with canvas in the past. At Mozilla’s recent Open Web Gaming conference, Ernesto Jiménez, lead developer at gaming company Six to Start, outlined some more handy tips for building canvas-based HTML5 games.

While a few of these tips are specific to games, in general they’re simply good ideas for anyone working with the canvas element — whether it’s games, animations or graphs.

Jiménez’s covers tips like drawing new elements offscreen and then copying them into your onscreen canvas to avoid flickering animations, and minimizing processor-intense operations like getImageData or fillText. He also talks about how to break up your animations into multiple canvas elements for smaller, faster graphics.

Jiménez’s slideshow gives a basic overview of the tips, but there’s also a video of the talk which includes a bit more detail on why these tips are helpful:

See Also:

File Under: Browsers

Chrome Gets New ‘Crankshaft’ Engine, Syncing, WebGL Support

SAN FRANCISCO, California — Google has rolled out some enhancements to its Chrome web browser, adding a new JavaScript engine, more hardware acceleration, and finalizing its system that keeps all of your copies of Chrome in sync.

The enhancements were debuted as part of a press event for Chrome OS and the Chrome Web Store here Tuesday.

The new JavaScript component is called Crankshaft, and it’s built on top of the open source V8 JavaScript engine that currently powers Chrome.

Google VP of product management Sundar Pichai says the boost makes Chrome 50 times as fast as web browsers were just two years ago when Chrome launched.

“Something that took a minute to happen in JavaScript two years ago can now happen in under a second,” he said.

We haven’t been able to verify Google’s speed claims yet (we’re still at the press event) but you can test out Crankshaft now. It’s available in the bleeding-edge Canary build of Chrome right now.

The syncing feature, which Google has had kicking around in developer and beta releases for months, offers “the same Chrome experience everywhere,” Pichai says. It syncs your bookmarks, preferences, auto-fill information and themes across all copies of Chrome, and you sync up your browsers by logging in to your Google Account. You can choose which datatypes you want to sync and which you don’t.

Also on display were the new WebGL features, which offload the most processor-intensive tasks for graphics and page rendering to the machine’s GPU. The demo featured the familiar “look at how fast the fish swim around the fish tank” method of showing off hardware acceleration, but Google added a nice touch by introducing sharks with lasers coming out of their eyes. The laser beams even refracted when they passed through the glass of the tank.

Google says Chrome 9 beta will have WebGL enabled.

Pichai also showed off some of Chrome’s other recent enhancements, like sandboxing for plug-ins.

He also said Chrome now boasts 120 million users worldwide.

See also:

File Under: Browsers

New IE9 Preview Arrives, Now With More JavaScript Power

Internet Explorer 9 Beta on the Windows 7 desktop

Microsoft pushed out another preview release of Internet Explorer 9 Wednesday. This is not a new beta release — we’re still months away from the official release of Internet Explorer 9 — but we’re definitely approaching the finish line.

Wednesday’s release, dubbed Internet Explorer 9 Platform Preview 7 (whew) includes a big performance boost with a newly revamped JavaScript engine inside of it.

The last preview release of IE9, which only arrived a few weeks ago, saw increased support for web standards. But Microsoft made it clear to us during a phone briefing that Wednesday’s release is all about speed and performance.

To that point, PP7 contains an updated version of the Chakra JavaScript engine. This new engine for IE9 was first introduced at Microsoft’s PDC developer event in November 2009. During the last year, the company has been improving Chakra to the point where it’s now scoring over 300 percent higher on the WebKit SunSpider benchmark than it was at launch.

Microsoft’s Ryan Gavin from the IE team says the new release scores 234.6 ms on SunSpider’s JavaScript execution performance test. Read more about the testing stuff on the IE Blog.

While some browsers are certainly faster than others, the major browser vendors continue to tweak their internal workings and make small improvements to speed. JavaScript performance is particularly important, since modern web applications like Gmail, Facebook and Twitter rely heavily on scripted actions. A faster browser means a snappier web app. Just last week, Mozilla released a new beta of Firefox 4 that included revamped code for its JägerMonkey and TraceMonkey JavaScript engines.

You can download this early version of the next IE browser directly from Microsoft. It’s available for PCs running Windows 7 and Vista. Also, this platform preview can be installed alongside IE9 Beta or IE8 with no problems.

Once you grab it, head over to the company’s demo playground and put the new browser through the paces. Be sure to report your results in the comments.

Continue Reading “New IE9 Preview Arrives, Now With More JavaScript Power” »

File Under: CSS, Visual Design

Lettering.js Makes Complex Typography Easy

CSS 3 adds some awesome new tools to web designers’ toolkit — the ability to rotate, transform and tweak elements means complex layouts can be done with nothing more than some style sheet rules.

Combine that with some of the fancy new fonts available through web services like Typekit and Fonts.com and you’re well on your way to replicating the kind of fine-tuned typography control print designers have long enjoyed. However, targeting individual letters and words can still be tricky.

That’s where Lettering.js comes in. The JQuery plugin can wrap your text with span tags, allowing you to target CSS rules to individual letters, words or sentences.

If you wondered how the designers behind the Lost World’s Fairs CSS experiment did it, well, look no further than Lettering.js. The other showcase examples on the Lettering.js website are no less impressive.

The library, which requires JQuery, can be downloaded from Github. Using it is as simple as selecting the element you want to target and applying the appropriate function — basically, whether to wrap the letters, words or lines of your target element.

One thing to note, the developers recommend putting Lettering.js in your head tags to avoid the unsightly flash of unstyled content that can occur if you include it at the bottom of your page.

See Also: