Mozilla

JavaScript Articles

Sort by:

View:

  1. MDN Learning: A place to ratchet your Web development skills

    If you’re looking to improve your Web development skills, we have compiled some great resources from around the Web to help every level of developer dig into their favorite open Web technologies. Our new MDN Learning space serves as a starting point for anyone interested in learning more about Web development. While there is already awesome documentation on MDN, not everyone knows how to find it — or other great tutorials and examples scattered around the Web. There is just so much content out there, we felt it was time to create a central place developers can go to quickly find the best resources.

    MDN Learning

    Our initial set of pages focus on documentation, tutorials, and other content for learning HTML, CSS and JavaScript. We will continue to add new content, including MDN Learning pages for topics like video, audio, webGL, etc. We also plan to use this new space to share more information about our collaboration with other organizations and projects that are developing open models around education, like P2PU’s School of Webcraft.

    This launch of MDN Learning is just the beginning of what we hope will become a permanent place on MDN for everything related to educating people about Web development and the resources available to them on not just MDN, but around the Web. We look forward to feedback and suggestions on how we can improve on this first step towards expanding MDN to cater to those getting started with developing for the Web.

  2. Accessibility and web innovation – a constant struggle

    I just came back from a small “accessibility tour” giving a talk about accessibility and web innovation in Stockholm, Sweden at Funkas Tillgänglighetsdagar and then in Paris at the W3Cafe meetup.

    In essence what I was musing about is that there is still a massive disconnect between accessibility and the development world. Accessibility is not seen as something that is cool and bleeding edge but as a necessary evil. If you ask about accessibility on developer mailing lists that juggle HTML5, Node.js, CSS3 and other cool technologies with ease you are very likely to hear that people are considering as an afterthought or make sure that “the interface degrades gracefully”.

    When you ask the accessibility world about cool new technologies you are very likely to hear that they may be interesting in a few years but are not ready yet and certainly will never be accessible in a legal sense.

    Having been positioned in between these two parties for a long time I am getting tired of this and I want the two fractions to move closer to each other.

    Accessibility is part of everything we do – the physical world has become much better in the last decades because we care for the needs of people with disabilities. Lowered kerbs on sidewalks, OCR Scanning, subtitles and captions on movies and TV programs – these are all things invented for a disability need but we all now benefit from it. The same can and should happen in interface design and web development. If you think about it, the features that make a good mobile interface also cover a lot of needs of different disability groups. So why don’t we work together?

    You can see the slides of the talk on Slideshare:

    You can get the slide deck on Slideshare:

    The audio of the talk is available at archive.org:

    There are also extensive notes on the talk available on my blog.

  3. Firefox 4 Performance

    Dave Mandelin from the JS team and Joe Drew from the Graphics team summarize the key performance improvements in Firefox 4.

    The web wants fast browsers. Cutting-edge HTML5 web pages play games, mash up and share maps, sound, and videos, show spreadsheets and presentations, and edit photos. Only a high-performance browser can do that. What the web wants, it’s our job to make, and we’ve been working hard to make Firefox 4 fast.

    Firefox 4 comes with performance improvements in almost every area. The most dramatic improvements are in JavaScript and graphics, which are critical for modern HTML5 apps and games. In the rest of this article, we’ll profile the key performance technologies and show how they make the web that much “more awesomer”.

    Fast JavaScript: Uncaging the JägerMonkey
    JavaScript is the programming language of the web, powering most of the dynamic content and behavior, so fast JavaScript is critical for rich apps and games. Firefox 4 gets fast JavaScript from a beast we call JägerMonkey. In techno-gobbledygook, JägerMonkey is a multi-architecture per-method JavaScript JIT compiler with 64-bit NaN-boxing, inline caching, and register allocation. Let’s break that down:

      Multi-architecture
      JägerMonkey has full support for x86, x64, and ARM processors, so we’re fast on both traditional computers and mobile devices. W00t!
      (Crunchy technical stuff ahead: if you don’t care how it works, skip the rest of the sections.)

      Per-method JavaScript JIT compilation

      The basic idea of JägerMonkey is to translate (compile) JavaScript to machine code, “just in time” (JIT). JIT-compiling JavaScript isn’t new: previous versions of Firefox feature the TraceMonkey JIT, which can generate very fast machine code. But some programs can’t be “jitted” by TraceMonkey. JägerMonkey has a simpler design that is able to compile everything in exchange for not doing quite as much optimization. But it’s still fast. And TraceMonkey is still there, to provide a turbo boost when it can.

      64-bit NaN-boxing
      That’s the technical name for the new 64-bit formats the JavaScript engine uses to represent program values. These formats are designed to help the JIT compilers and tuned for modern hardware. For example, think about floating-point numbers, which are 64 bits. With the old 32-bit value formats, floating-point calculations required the engine to allocate, read, write, and deallocate extra memory, all of which is slow, especially now that processors are much faster than memory. With the new 64-bit formats, no extra memory is required, and calculations are much faster. If you want to know more, see the technical article Mozilla’s new JavaScript value representation.
      Inline caching
      Property accesses, like o.p, are common in JavaScript. Without special help from the engine, they are complicated, and thus slow: first the engine has to search the object and its prototypes for the property, next find out where the value is stored, and only then read the value. The idea behind inline caching is: “What if we could skip all that other junk and just read the value?” Here’s how it works: The engine assigns every object a shape that describes its prototype and properties. At first, the JIT generates machine code for o.p that gets the property by laborious searching. But once that code runs, the JITs finds out what o's shape is and how to get the property. The JIT then generates specialized machine code that simply verifies that the shape is the same and gets the property. For the rest of the program, that o.p runs about as fast as possible. See the technical article PICing on JavaScript for fun and profit for much more about inline caching.

      Register allocation
      Code generated by basic JITs spends a lot of time reading and writing memory: for code like x+y, the machine code first reads x, then reads y, adds them, and then writes the result to temporary storage. With 64-bit values, that's up to 6 memory accesses. A more advanced JIT, such as JägerMonkey, generates code that tries to hold most values in registers. JägerMonkey also does some related optimizations, like trying to avoid storing values at all when they are constant or just a copy of some other value.

    Here's what JägerMonkey does to our benchmark scores:

    That's more than 3x improvement on SunSpider and Kraken and more than 6x on V8!

    Fast Graphics: GPU-powered browsing.
    For Firefox 4, we sped up how Firefox draws and composites web pages using the Graphics Processing Unit (GPU) in most modern computers.

    On Windows Vista and Windows 7, all web pages are hardware accelerated using Direct2D . This provides a great speedup for many complex web sites and demo pages.

    On Windows and Mac, Firefox uses 3D frameworks (Direct3D or OpenGL) to accelerate the composition of web page elements. This same technique is also used to accelerate the display of HTML5 video .

    Final take
    Fast, hardware-accelerated graphics combined plus fast JavaScript means cutting-edge HTML5 games, demos, and apps run great in Firefox 4. You see it on some of the sites we enjoyed making fast. There's plenty more to try in the Mozilla Labs Gaming entries and of course, be sure to check out the Web O' Wonder.

  4. Syncing page content with HTML5 video (a different kind of webinar)

    If you’ve been around the software industry for a little while, you’ve probably attended at least a few “webinars”, where someone does an online presentation, which you can watch and listen to in real time. You might be able to ask questions via a chat window, and if you’re lucky, the presenter will select your question to answer in the very limited time allocated for audience questions. If you can’t make it to the real-time presentation, you can watch a recording later, but you miss out on the Q&A.

    The Mozilla Developer Engagement team is experimenting with a slightly different approach to presenting webinars. We’re decoupling the presentation part from the Q&A part. Instead of a real-time presentation with a little bit of Q&A, we’re publishing a screencast, and scheduling time for online chat about it later.

    You can view the screencast on your own time, as much as you need to, and peruse and play with the code under discussion. Then, for those who have questions, the presenter will be on IRC during scheduled times to discuss them. You’ll also be able to chat with other participants, which usually isn’t possible in a typical webinar.

    Here is the first in an intended series of pseudo-webinars: Christian Heilmann talking about syncing page content with HTML5 video.

    The screencast

    The chats

    Discussion of this screencast will take place in the #mdnlearning channel on irc.mozilla.org at the following times:

    • 10:00 UTC, Monday, 21 March
    • 19:00 UTC, Monday, 21 March

    If you don’t have an IRC client installed (such as the Chatzilla add-on for Firefox), you can access the #mdnlearning channel via this Mibbit widget.

    We picked the times for the chat sessions to cover as many time zones as possible. We know they won’t be ideal for everybody. Please let us know in the comments how much lead time you’d like between publishing screencasts and the scheduled chats.

    The code

    The code that Chris demos in the screencast is available at https://github.com/codepo8/Syncing-Video.

  5. History API changes in Firefox 4

    This is a guest post by Jonas Sicking, one of the Gecko developers.

    As I’m sure you know we’re getting ready to ship Firefox 4. And as you
    might know Firefox 4 includes the history API (which includes the pushState() and replaceState() methods) defined in HTML5. This API is also implemented in Safari and Chrome, but Firefox 4 has important differences, which I describe in this post.

    A few weeks ago someone discovered a pretty big flaw in the pushState API. The problem is that if you use the state argument to pushState() or replaceState(), and the user later reloads page with such a state, there is no way to get access to said state until after the load event fires. This because the only way to get access to said state is through the popstate event which doesn’t fire until after load has fired.

    This means that for pages that use the state argument, the page has to render without knowledge of said state, and only after the page has been fully loaded can the correct state be shown to the user.

    Note that the “state” that I’m talking about here is the state argument passed to pushState()/replaceState(). The URL (which arguably is the much more useful argument to pushState()/replaceState()) is always accessible using the normal APIs like document.location and window.location.

    To fix this problem we are making two changes in our implementation compared to the current working draft:

    • Always expose the current state through a window.history.state property. This way a page immediately gets access to the current state of the page and doesn’t have to wait until the first popstate event fires.
    • Don’t always fire a popstate event right after the load event.
      Instead, only fire it during real session history transitions (i.e., when the user clicks Back or Forward or when history.back()/forward()/go() is called)

      The whole purpose of this extra popstate event was to give access to the page’s state. However the window.history.state property makes this redundant. We have found that pages just find this event unexpected and a source of bugs.

    The first change should be fully backwards compatible since it’s a purely additive change. It doesn’t affect existing code, which presumably doesn’t use this property.

    The second change is the bigger concern. If your code is expecting this event to always fire, then this might result in problems. Another thing that alleviates the risk with this change is that Safari 5 appears to have misunderstood the working draft on this issue, and doesn’t fire this popstate unless a state is specifically passed to pushState()/replaceState(). So basically Firefox will behave like Safari 5 as long as you don’t use the state argument.

    We are also making a third change:

    • Allow popstate to fire while the page is loading.

    The working draft currently has a somewhat surprising limitation in that it forbids any popstate events from firing before the load event for a page has fired. If the user clicks on a pushState-backed link while the page is loading (for example due to a slow-loading image), and then presses the Back button, no popstate event fires. Only after the load event for the page has fired is the first popstate allowed to fire. We have removed this limitation and always fire popstate when the Back or Forward button is pressed or when history.back()/forward()/go() is called.

    I have done some testing and so far have not seen any problems due to these changes. Unfortunately, due to discovering these problems so late, these changes won’t appear in Firefox betas until Firefox 4 RC. There are test builds available, which you can test with right away.

  6. Multimedia on the web and using HTML5 sensibly

    Last week I went to the London Ajax User Meetup in London, England to deliver two talks about HTML5. One was a re-run of a talk I gave at MIT about Multimedia on the web and the second was a call to arms to use HTML5 sensibly. You can go over to Skillsmatter web site to see both talks back to back – but be sure to catch the notes to the second talk in this post, too.

    In addition to my notes here there is also a great write-up of the evening by Ian Alderson available on the web.

    Multimedia on the web

    We’ve covered this talk before in the blog post here and you can read the extensive notes for the whole talk with code examples on my blog. The slides of the multimedia talk are on slideshare and here:

    You can see “Multimedia on the web” on any HTML5 enabled device here (courtesy of vid.ly) or embedded here:

    Using HTML5 sensibly

    Using HTML5 sensibly was a talk I wanted to give for a long time. Rather than just giving the facts, I wanted to raise some questions every developer should ask themselves, the HTML5 working groups and everyone who cares to listen. We are in the middle of a big change in our development environment and not many people realise that we are breaking a lot of old conventions without fallback.

    You can get the slides on Slideshare or see them here:

    You can see “Using HTML5 sensibly” on any HTML5 enabled device here (courtesy of vid.ly).

    Notes on “Using HTML5 sensibly”

    I started the talk by telling the story of the Antarctic Snow Cruiser – a marvel of technology built in 1939 to allow a crew to explore Antarctica. The job of the Cruiser was to give the crew all the neccesary creature comforts and allow them to drive through Antarctica, which is both very cold and also features massive cracks that the vehicle somehow needs to get over. The ingenious solution was to have huge wheels that can be retracted into the Cruiser to prevent them from getting brittle over night and to push the vehicle over the cracks. The Cruiser was built in a rush and tested on the way to the port to go down to Antarctica. It was a hit with the press and people delayed the whole trip even more by wanting to have their photo taken with it. Upon arrival the vehicle almost crashed into the sea as the ramp built for its delivery onto the ice was not strong enough. Even worse, once on the ice the Cruiser couldn’t get a grip and the wheels spun uselessly, almost overheating the engine. Despite all the hype, the cruiser was a massive failure.

    A few things went wrong with the cruiser:

    • It was purely engineering driven
    • It was tested while on the road
    • It was never tested in the real environment
    • There was a massive media excitement before it proved its worth

    Much like we deal with HTML5 nowadays. A lot of the information about HTML5 is marketing driven and used to sell a certain environment or browser to people. Instead of real applications and day-to-day use web sites we create demo sites to show what “HTML5 can do for you”. The term HTML5 gets washed out as it is used both for implementations of parts of the specification but also for browser-specific code that only works in a certain environment.

    This is partly because of the specifications and the different players in the HTML5 world itself. The specs do not only contain definitions of markup but also JavaScript APIs and instructions on how to write a browser that renders HTML5 content. This is great as it takes away the liberty browser vendors had in the past in “creatively” applying the HTML4 specs, but it also means that people can focus on parts of the spec and of course rant about all the other parts. You’ve probably seen one talk about the amazing cool new semantics of HTML5 markup and another about API implementations using completely non-sensical markup back to back. This is what we get right now as the specs are too big and all-encompassing for implementers.

    One of the main topics of the HTML5 work is pragmatism – XML and strict HTML just used too many things we simply don’t need. This shows itself a lot in the simplification of a plain HTML document. In HTML4.01 strict this was:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html lang="en">
    <head>
      <meta http-equiv="Content-Type" 
            content="text/html; charset=UTF-8">  
      <title>HTML - c'est moi!</title>
      <link rel="stylesheet" type="text/css"
            href="styles.css">
      <script type="text/javascript" src="magic.js">
      </script>
    </head>
    <body>
      <h1>Heading! Everybody duck!</h1>
      <p>I am content, hear me roar!</p>
      <p class="footer">By me!</p>
    </body>
    </html>

    Neither the long DOCTYPE definition nor the http-equiv was ever used by browsers. It is not needed for browsers to do their job. In HTML5 this is a plain Vanilla document:

    <!DOCTYPE html>  
    <html lang="en">
    <head>
      <meta charset="utf-8">  
      <title>HTML5, c'est moi, ou HTML...</title>
      <link rel="stylesheet" href="styles.css">
      <script src="magic.js"></script>
    </head>
    <body>
      <h1>Heading! Everybody duck!</h1>
      <p>I am content, hear me roar!</p>
      <p class="footer">By me!</p>
    </body>
    </html>

    Much simpler and shorter. In addition to that HTML5 also includes new semantic elements:

    <!DOCTYPE html>  
    <html lang="en">
    <head>
      <title>HTML5, c'est moi, ou HTML...</title>
      <link rel="stylesheet" href="styles.css">
      <script src="magic.js"></script>
    </head>
    <body>
      <header><h1>Heading! Everybody duck!</h1></header>
      <section>
        <p>I am content, hear me roar!</p>
      </section>
      <footer><p>By me!</p></footer>
    </body>
    </html>

    This gives us handles for styling and tells the browser what the different parts are. The simplification goes further though. As people never seemed to have bothered to write valid XML in HTML it is now also completely OK to mix upper and lower case and omit quotation marks around the attributes (if the attributes have one value, multi value attributes like classes need quotes around them once you add more than one value):

    <!DOCTYPE html>  
    <html lang=en>
      <TITLE>HTML5, c'est moi, ou HTML...</title>
      <LINK rel=stylesheet href=styles.css>
      <script src=magic.js></SCRIPT>
    <body>
      <HEADER><h1>Heading! Everybody duck!</h1></header>
      <section>
        <p>I am content, hear me roar!</p>
      </SECTION>
      <footer><p>By me!</p></FOOTER>
    </body>
    </HTML>

    Browsers are forgiving enough to fix these inconsistencies for us. For example the generated code in Firefox is:

    <!DOCTYPE html>  
    <html lang="en"><head>  
      <title>HTML5, c'est moi, ou HTML...</title>
      <link rel="stylesheet" href="styles.css">
      <script src="magic.js"></script>
      </head><body>
      <header><h1>Heading! Everybody duck!</h1></header>
      <section>
        <p>I am content, hear me roar!</p>
     
      </section>
      <footer><p>By me!</p></footer>
    </body></html>

    However, if we were to omit the closing </p> tag in the <section> the generated code looks different:

    <!DOCTYPE html>
    <html lang="en"><head>  
      <title>HTML5, c'est moi, ou HTML...</title>
      <link rel="stylesheet" href="styles.css">
      <script src="magic.js"></script>
    </head><body>
      <header><h1>Heading! Everybody duck!</h1></header>
      <section>
        <p>I am content, hear me roar!
          <footer></footer>
        </p>
        <p>By me!</p>
      </section>
    </body></html>

    As you can see, the <footer> got moved into the paragraph inside the section. Why? Who knows? The issue is that we ask a browser to make an educated guess for us and as a browser doesn’t understand semantics, this is what we get.

    Which leads me to a few questions we need to ask and find the answer to:

    • Can innovation be based on “people never did this correctly anyways”?
    • Is it HTML or BML? (HyperText Markup Language or Browser Markup Language)
    • Should HTML be there only for browsers? What about conversion Services? Search bots? Content scrapers?

    The next issue I wanted to discuss is legacy browsers which seems to be a euphemism for IE6. The issue with IE6 is that when you use the new semantic HTML elements exclusively then they can’t be styled in this browser. By using the correct new syntax that should bring us a lot of benefits you condemn older browser users to see unstyled documents.

    There are a few ways around this. The first one requires JavaScript – if you create the element using the DOM first you can style it in IE:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <style>header{color:#fff;background:#369;}</style>
      <script>document.createElement('header');</script>
    </head>
    <body>
      <header><h1>Hello!</h1></header>
    </body>
    </html>

    This technique has been wrapped up nicely in a script called HTML5 shiv by Remy Sharp. Of course, this means that you make markup dependent on JavaScript to work which is not what markup is about, according to purists of the web. You can work around that dependency in a few ways. You can write HTML5 as XHTML, you can use conditional comments or a namespace or you can use both the new semantic elements and DIVs with a class around them to please all browsers:

    <!DOCTYPE html>
    <html lang="en">
      <head><meta charset="utf-8">
        <title>HTML5, c'est moi, ou HTML...</title>
        <link rel="stylesheet" href="styles.css">
        <script src="magic.js"></script>
        <style type="text/css" media="screen">
          .header,header,
          .footer,footer,
          .aside,aside,
          .section,section{
            display:block;
          }
        </style>
      </head>
      <body>
      <div class="header"><header>
        <h1>Heading! Everybody duck!</h1>
      </header></div>
      <div class="section"><section>
        <p>I am content, hear me roar!</p>
      </section></div>
      <div class="footer"><footer>
        <p>By me!</p>
      </footer></div>
    </body>
    </html>

    This seems to be the most pragmatic solution but is a lot of extra effort.

    The main issue is that not only legacy browsers are failing to support HTML5 properly which is why people tend to use a library like Modernizr to check for HTML5 support before applying it. Modernizr adds classes to the HTML element after checking what the current browser supports and thus gives you handles to use in progressive enhancement. All the hacks and fixes are also bundled in HTML5 Boilerplate, including server settings and ways to make legacy browsers behave. In essence, the much smaller Vanilla HTML5 markup becomes a lot of code again if you test it in the real world.

    If you also want to use all the cool new JavaScript APIs you can use Polyfills to make legacy browsers do something with the code you write.

    Which leads to more questions we need to answer:

    • Should we shoe-horn new technology into legacy browsers?
    • Do patches add complexity as we need to test their performance? (there is no point in giving an old browser functionality that simply looks bad or grinds it down to a halt)
    • How about moving IE fixes to the server side? Padding with DIVs with classes in PHP/Ruby/Python after checking the browser and no JS for IE?

    The last feature of HTML5 I want to talk about is Video and Audio. Again, there is much more complexity than meets the eye:

    Tecnically, embedding an HTML5 video should be as simple as this:

    <video src="interview.ogv" controls>
      <a href="interview.ogv">Download the video</a>
    </video>

    Once you consider all the different formats needed for different browsers though it becomes a lot more work:

    <video controls>
      <source src="interview.mp4" type="video/mp4">
      </source>
      <source src="interview.webm" type="video/webm">
      </source>
      <source src="interview.ogv" type="video/ogg">
      </source>
      <p>Download the 
        <a href="interview.mp4">video in MP4 format</a>.
      </p>
    </video>

    The reason is intellectual property, legal codec battles and implementation of video in different browsers and platforms. In essence, you need to provide the video in three formats. Of course when there is a need then some company will come up with a solution. Vid.ly is a service by encoding.com that provides you with a single URL that sends the video in the right format to the device you use. All in all they create 28 different formats for you to cater for all kind of mobiles and browsers.

    The other big issue with HTML5 video is that there is no protection from downloading the videos. This is as intended but a big problem when it comes to premium content on the web. As discussed in the comments of this post by Adobe publishers want to have a way to stop people from downloading and reusing their videos but instead just want their audience to watch them in a closed environment.

    All in all there are a few questions to answer when it comes to HTML5 video:

    • Can we expect content creators to create video in many formats to support an open technology?
    • Can a service like vid.ly be trusted for content creation and storage?
    • Is HTML5 not applicable for premium content?

    In the end, I want every developer and designer out there to take a stand and demand answers to these questions. There is no point in just saying “that’s how it is”. When we keep our technologies closed and when we rely on scripting to make web sites work we do break the web in the long run. The current debate about hashbangs for links shows this.

    Everybody can take part in the HTML5 working group and add documentation to MDN – time to get to work.

  7. Jolicloud – a web standards based OS

    Seeing what other people do in an audience at a conference can be interesting. When waiting for the next talk in the incredibly claustrophobic seats at FOSDEM last week I saw something that got my attention: the Desktop of an operating system being debugged using a web inspector:

    Jolicloud OS debugging :)

    Turns out, the guys doing that are from Jolicloud – a company that strives to offer a OS alternative for old and low-spec computers by only providing basic OS tasks and leaving the day-to-day work tasks to web applications hosted in the cloud. Sounds familiar? Google does the same with their Chrome OS and the Cr48. The main difference is that Jolicloud is based in Europe and a dedicated, affordable Netbook is available even for us across the pond.

    Jolicloud is an interesting approach to fix the problem of outdated hardware and any Desktop system that runs on HTML, CSS and JavaScript gets my attention. Hence I took the opportunity to interview the guys on the spot and get some answers:

    You can see the video on any HTML5 enabled device here (courtesy of vid.ly).

    If you want to give Jolicloud a try you can check it out at http://www.jolicloud.com/.

  8. An interesting way to determine if you are logged into social web sites

    Do you remember the trick how to find out that you went to certain web sites by analysing link colour (now patched in Firefox)? There is much your browser tells about you if you just create a few HTML elements.

    Mike Cardwell has found an interesting way to detect if you are logged into social web sites. The easiest trick lies with GMail. Mike created a photo and uploaded it to Google. If you add this image to an HTML document and add event handlers for the success and failure case you can check if the visitor is logged in or not – as the photo gets delivered when you are and GMail delivers a 404 document when you are not:

    <img style="display:none;"
         onload="logged_in_to_gmail()"
         onerror="not_logged_in_to_gmail()"
         src="https://mail.google.com/mail/photos/static/AD34hIhNx1pdsCxEpo6LavSR8dYSmSi0KTM1pGxAjRio47pofmE9RH7bxPwelO8tlvpX3sbYkNfXT7HDAZJM_uf5qU2cvDJzlAWxu7-jaBPbDXAjVL8YGpI"
    />

    This works in all browsers and can be used to for example send mailto: links to GMail directly. Notice that this just checks that you are logged in, it doesn’t mean you get access to content.

    For Facebook and Twitter, this doesn’t quite work. Instead, Mike tries to read content with the APIs and relies on errors to be thrown on 404 responses:

    <script type="text/javascript"
            src="https://twitter.com/account/use_phx?setting=false&amp;format=text"
            onload="not_logged_in_to_twitter()"
            onerror="logged_in_to_twitter()"
            async="async"
    ></script>
     
    <script type="text/javascript"
            src="https://www.facebook.com/imike3"
            onload="logged_in_to_facebook()"
            onerror="not_logged_in_to_facebook()"
            async="async"
    ></script>

    This fails to work in Internet Explorer and Opera, but still works nicely for the other browsers. In Firefox you can work around this using the Request Policy add-on.

    It’d be interesting to see what other social web sites can be detected with some simple onload and onerror handlers. Know any others?

  9. ECMAScript 5 strict mode in Firefox 4

    Editor’s note: This article is posted by Chris Heilmann but authored by Jeff Walden – credit where credit is due.

    Developers in the Mozilla community have made major improvements to the JavaScript engine in Firefox 4. We have devoted much effort to improving performance, but we’ve also worked on new features. We have particularly focused on ECMAScript 5, the latest update to the standard underlying JavaScript.

    Strict mode is arguably the most interesting new feature in ECMAScript 5. It’s a way to opt in to a restricted variant of JavaScript. Strict mode isn’t just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don’t rely on strict mode without feature-testing for support for the relevant aspects of strict mode.

    Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. Strict mode blazes a path to future ECMAScript editions where new code with a particular <script type="..."> will likely automatically be executed in strict mode.

    What does strict mode do? First, it eliminates some JavaScript pitfalls that didn’t cause errors by changing them to produce errors. Second, it fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode. Firefox 4 generally hasn’t optimized strict mode yet, but subsequent versions will. Third, it prohibits some syntax likely to be defined in future versions of ECMAScript.

    Invoking strict mode

    Strict mode applies to entire scripts or to individual functions. It doesn’t apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, event handler attributes, strings passed to setTimeout, and the like are entire scripts, and invoking strict mode in them works as expected.

    Strict mode for scripts

    To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

    // Whole-script strict mode syntax
    "use strict";
    var v = "Hi!  I'm a strict mode script!";

    This syntax has a trap that has already bitten a major site: it isn’t possible to blindly concatenate non-conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine. Only crossing the streams by concatenating strict and non-strict scripts is problematic.

    Strict mode for functions

    Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function’s body before any other statements.

    function strict()
    {
      // Function-level strict mode syntax
      'use strict';
      function nested() { return "And so am I!"; }
      return "Hi!  I'm a strict mode function!  " + nested();
    }
    function notStrict() { return "I'm not strict."; }

    Changes in strict mode

    Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories:

    • Converting mistakes into errors (as syntax errors or at runtime)
    • Simplifying how the particular variable for a given use of a name is computed
    • Simplifying eval and arguments
    • Making it easier to write “secure” JavaScript
    • Anticipating future ECMAScript evolution

    Converting mistakes into errors

    Strict mode changes some previously-accepted mistakes into errors. JavaScript was designed to be easy for novice developers, and sometimes it gives operations which should be errors non-error semantics. Sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. Strict mode treats these mistakes as errors so that they’re discovered and promptly fixed.

    First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript, mistyping a variable in an assignment creates a new property on the global object and continues to “work” (although future failure is possible: likely, in modern JavaScript). Assignments which would accidentally create global variables instead throw errors in strict mode:

    "use strict";
    mistypedVaraible = 17; // throws a ReferenceError

    Second, strict mode makes assignments which would otherwise silently fail throw an exception. For example, NaN is a non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN throws an exception. Any assignment that silently fails in normal code will throw errors in strict mode:

    "use strict";
    NaN = 42; // throws a TypeError
    var obj = { get x() { return 17; } };
    obj.x = 5; // throws a TypeError
    var fixed = {};
    Object.preventExtensions(fixed);
    fixed.newProp = "ohai"; // throws a TypeError

    Third, if you attempt to delete undeletable properties, strict mode throws errors (where before the attempt would simply have no effect):

    "use strict";
    delete Object.prototype; // throws a TypeError

    Fourth, strict mode requires that all properties named in an object literal be unique. Normal code may duplicate property names, with the last one determining the property’s value. But since only the last one does anything, the duplication is simply a vector for bugs, if the code is modified to change the property value other than by changing the last instance. Duplicate property names are a syntax error in strict mode:

    "use strict";
    var o = { p: 1, p: 2 }; // !!! syntax error

    Fifth, strict mode requires that function argument names be unique. In normal code the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through arguments[i], so they’re not completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error:

    function sum(a, a, c) // !!! syntax error
    {
      "use strict";
      return a + b + c; // wrong if this code ran
    }

    Sixth, strict mode forbids octal syntax. Octal syntax isn’t part of ECMAScript, but it’s supported in all browsers by prefixing the octal number with a zero: 0644 === 420 and "\\045" === "%". Novice developers sometimes believe a leading zero prefix has no semantic meaning, so they use it as an alignment device — but this changes the number’s meaning! Octal syntax is rarely useful and can be mistakenly used, so strict mode makes octal a syntax error:

    "use strict";
    var sum = 015 + // !!! syntax error
              197 +
              142;

    Simplifying variable uses

    Strict mode simplifies how variable uses map to particular variable definitions in the code. Many compiler optimizations rely on the ability to say that this variable is stored in this location: this is critical to fully optimizing JavaScript code. JavaScript sometimes makes this basic mapping of name to variable definition in the code impossible to perform except at runtime. Strict mode removes most cases where this happens, so the compiler can better optimize strict mode code.

    First, strict mode prohibits with. The problem with with is that any name in it might map either to a property of the object passed to it, or to a variable in surrounding code, at runtime: it’s impossible to know which beforehand. Strict mode makes with a syntax error, so there’s no chance for a name in a with to refer to an unknown location at runtime:

    "use strict";
    var x = 17;
    with (obj) // !!! syntax error
    {
      // If this weren't strict mode, would this be var x, or
      // would it instead be obj.x?  It's impossible in general
      // to say without running the code, so the name can't be
      // optimized.
      x;
    }

    The simple alternative of assigning the object to a variable, then accessing the corresponding property on that variable, stands ready to replace with.

    Second, eval of strict mode code does not introduce new variables into the surrounding code. In normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval, every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval creates variables only for the code being evaluated, so eval can’t affect whether a name refers to an outer variable or some local variable:

    var x = 17;
    var evalX = eval("'use strict'; var x = 42; x");
    assert(x === 17);
    assert(evalX === 42);

    Relatedly, if the function eval is invoked by an expression of the form eval(...) in strict mode code, the code will be evaluated as strict mode code. The code may explicitly invoke strict mode, but it’s unnecessary to do so.

    function strict1(str)
    {
      "use strict";
      return eval(str); // str will be treated as strict mode code
    }
    function strict2(f, str)
    {
      "use strict";
      return f(str); // not eval(...): str is strict iff it invokes strict mode
    }
    function nonstrict(str)
    {
      return eval(str); // str is strict iff it invokes strict mode
    }
    strict1("'Strict mode code!'");
    strict1("'use strict'; 'Strict mode code!'");
    strict2(eval, "'Non-strict code.'");
    strict2(eval, "'use strict'; 'Strict mode code!'");
    nonstrict("'Non-strict code.'");
    nonstrict("'use strict'; 'Strict mode code!'");

    Third, strict mode forbids deleting plain names. Thus names in strict mode eval code behave identically to names in strict mode code not being evaluated as the result of eval. Using delete name in strict mode is a syntax error:

    "use strict";
    eval("var x; delete x;"); // !!! syntax error

    Making eval and arguments simpler

    Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in normal code: eval to add or remove bindings and to change binding values, and arguments by its indexed properties aliasing named arguments. Strict mode makes great strides toward treating eval and arguments as keywords, although full fixes will not come until a future edition of ECMAScript.

    First, the names eval and arguments can’t be bound or assigned in language syntax. All these attempts to do so are syntax errors:

    "use strict";
    eval = 17;
    arguments++;
    ++eval;
    var obj = { set p(arguments) { } };
    var eval;
    try { } catch (arguments) { }
    function x(eval) { }
    function arguments() { }
    var y = function eval() { };
    var f = new Function("arguments", "'use strict'; return 17;");

    Second, strict mode code doesn’t alias properties of arguments objects created within it. In normal code within a function whose first argument is arg, setting arg also sets arguments[0], and vice versa (unless no arguments were provided or arguments[0] is deleted). For strict mode functions, arguments objects store the original arguments when the function was invoked. The value of arguments[i] does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i].

    function f(a)
    {
      "use strict";
      a = 42;
      return [a, arguments[0]];
    }
    var pair = f(17);
    assert(pair[0] === 42);
    assert(pair[1] === 17);

    Third, arguments.callee is no longer supported. In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. For strict mode functions, arguments.callee is a non-deletable property which throws an error when set or retrieved:

    "use strict";
    var f = function() { return arguments.callee; };
    f(); // throws a TypeError

    “Securing” JavaScript

    Strict mode makes it easier to write “secure” JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website on behalf of other users. JavaScript in browsers can access the user’s private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality. JavaScript’s flexibility makes it effectively impossible to do this without many runtime checks. Certain language functions are so pervasive that performing runtime checks has considerable performance cost. A few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in a certain manner, substantially reduce the need for those runtime checks.

    First, the value passed as this to a function in strict mode isn’t boxed into an object. For a normal function, this is always an object: the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify a particular this.) Automatic boxing is a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality “secure” JavaScript environments must invariably. Thus for a strict mode function, the specified this is used unchanged:

    "use strict";
    function fun() { return this; }
    assert(fun() === undefined);
    assert(fun.call(2) === 2);
    assert(fun.apply(null) === null);
    assert(fun.call(undefined) === undefined);
    assert(fun.bind(true)() === true);

    (Tangentially, built-in methods also now won’t box this if it is null or undefined. [This change is independent of strict mode but is motivated by the same concern about exposing the global object.] Historically, passing null or undefined to a built-in method like Array.prototype.sort() would act as if the global object had been specified. Now passing either value as this to most built-in methods throws a TypeError. Booleans, numbers, and strings are still boxed by these methods: it’s only when these methods would otherwise act on the global object that they’ve been changed.)

    Second, in strict mode it’s no longer possible to “walk” the JavaScript stack via commonly-implemented extensions to ECMAScript. In normal code with these extensions, when a function fun is in the middle of being called, fun.caller is the function that most recently called fun, and fun.arguments is the arguments for that invocation of fun. Both extensions are problematic for “secure” JavaScript, because they allow “secured” code to access “privileged” functions and their (potentially unsecured) arguments. If fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw an error when set or retrieved:

    function restricted()
    {
      "use strict";
      restricted.caller;    // throws a TypeError
      restricted.arguments; // throws a TypeError
    }
    function privilegedInvoker()
    {
      return restricted();
    }
    privilegedInvoker();

    Third, arguments for strict mode functions no longer provide access to the corresponding function call’s variables. In some old ECMAScript implementations arguments.caller was an object whose properties aliased variables in that function. This is a security hazard because it breaks the ability to hide privileged values via function abstraction; it also precludes most optimizations. For these reasons no recent browsers implement it. Yet because of its historical functionality, arguments.caller for a strict mode function is also a non-deletable property which throws an error when set or retrieved:

    "use strict";
    function fun(a, b)
    {
      "use strict";
      var v = 12;
      return arguments.caller; // throws a TypeError
    }
    fun(1, 2); // doesn't expose v (or a or b)

    Paving the way for future ECMAScript versions

    Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition. It will be easier to make some changes if the foundations of those changes are prohibited in strict mode.

    First, in strict mode a short list of identifiers become reserved keywords. These words are implements, interface, let, package, private, protected, public, static, and yield. In strict mode, then, you can’t name or use variables or arguments with these names. A Mozilla-specific caveat: if your code is JavaScript 1.7 or greater (you’re chrome code, or you’ve used the right <script type="">) and is strict mode code, let and yield have the functionality they’ve had since those keywords were first introduced. But strict mode code on the web, loaded with <script src=""> or <script>...</script>, won’t be able to use let/yield as identifiers.

    Second, strict mode prohibits function statements not at the top level of a script or function. In normal code in browsers, function statements are permitted “everywhere”. This is not part of ES5! It’s an extension with incompatible semantics in different browsers. Future ECMAScript editions hope to specify new semantics for function statements not at the top level of a script or function. Prohibiting such function statements in strict mode “clears the deck” for specification in a future ECMAScript release:

    "use strict";
    if (true)
    {
      function f() { } // !!! syntax error
      f();
    }
    for (var i = 0; i &lt; 5; i++)
    {
      function f2() { } // !!! syntax error
      f2();
    }
    function baz() // kosher
    {
      function eit() { } // also kosher
    }

    This prohibition isn’t strict mode proper, because such function statements are an extension. But it is the recommendation of the ECMAScript committee, and browsers will implement it.

    Strict mode in browsers

    Firefox 4 is the first browser to fully implement strict mode. The Nitro engine found in many WebKit browsers isn’t far behind with nearly-complete strict mode support. Chrome has also started to implement strict mode. Internet Explorer and Opera haven’t started to implement strict mode; feel free to send those browser makers feedback requesting strict mode support.

    Browsers don’t reliably implement strict mode, so don’t blindly depend on it. Strict mode changes semantics. Relying on those changes will cause mistakes and errors in browsers which don’t implement strict mode. Exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant features of strict mode are implemented.

    To test out strict mode, download a Firefox nightly and start playing. Also consider its restrictions when writing new code and when updating existing code. (To be absolutely safe, however, it’s probably best to wait to use it in production until it’s shipped in browsers.)

  10. Zooming and rotating for video in HTML5 and CSS3

    The source of the code examples in this post is available on GitHub and you can see the demo in action.

    There are dozens of video players that allow you to do all the normal things with videos: play, pause, jump to a certain time and so on. More advanced ones also allow you to fast forward and reverse the video and support subtitles.

    One thing I haven’t found yet though is zooming and rotation of a video. Granted, an edge use case, but sometimes it is cool to be able to zoom into a detail like a blooper (boom mic in the background) or an easter egg (check for the term “A 113″ in every Pixar movie – an homage to the classroom most of the original Pixar cast learned their trade in).

    Rotation might come in handy when you recorded your video in portrait instead of landscape on your camera and you don’t want to re-encode it before you put it on the web.

    The HTML5 video tag allows you to style the video with CSS and CSS3 transforms allow both for scaling and for rotation. So let’s put those together.

    Embedding a video is as simple as this (see this in action on the demo page):

    <video controls>
      <source src="http://www.archive.org/download/AnimatedMechanicalArtPiecesAtMit/P1120973_512kb.mp4" type="video/mp4">         
      <source src="http://www.archive.org/download/AnimatedMechanicalArtPiecesAtMit/P1120973.ogv" type="video/ogg">
      <p>Your browser doesn't support the HTML5 video tag it seems. 
         You can see this video as part of a collection <a href="http://www.archive.org/download/AnimatedMechanicalArtPiecesAtMit/">at archive.org</a>.</p>         
    </video>

    Now, to scale this video you can use CSS3 transform:scale:

    Scaling a video with CSS3 transformations

    video{
      display:block;
      width:400px;
      height:300px;
    }
    video.scale2{
      -moz-transform:scale(1.5);
      -webkit-transform:scale(1.5);
      -o-transform:scale(1.5);
      -ms-transform:scale(1.5);
      transform:scale(1.5);
    }

    You can rotate with CSS3 transform:rotate:

    Rotate a video with CSS3 transformations

    video{
      -moz-transform:rotate(20deg);
      -webkit-transform:rotate(20deg);
      -o-transform:rotate(20deg);
      -ms-transform:rotate(20deg);
      transform:rotate(20deg);
    }

    And you can do both:

    Rotate and scale a video with CSS3 transformations

    video{
      -moz-transform:scale(1.5) rotate(20deg);
      -webkit-transform:scale(1.5) rotate(20deg);
      -o-transform:scale(1.5) rotate(20deg);
      -ms-transform:scale(1.5) rotate(20deg);
      transform:scale(1.5) rotate(20deg);
    }

    Now, this doesn’t make much sense though as it changes the dimension of the video (in the demo page I needed to change the margin for each video accordingly). To really provide a “zoom” functionality, we’d need to keep the original size and cut off the parts we don’t need. We could do this using a CANVAS element, but why go that far when a simple DIV does the job for us?

    All we need to do to keep the space is nest our videos in a DIV with the class stage:

    <div class="stage"><video controls>
      <source src="http://www.archive.org/download/AnimatedMechanicalArtPiecesAtMit/P1120973_512kb.mp4" type="video/mp4">         
      <source src="http://www.archive.org/download/AnimatedMechanicalArtPiecesAtMit/P1120973.ogv" type="video/ogg">         
      <p>Your browser doesn't support the HTML5 video tag it seems. 
         You can see this video as part of a collection <a href="http://www.archive.org/download/AnimatedMechanicalArtPiecesAtMit/">at archive.org</a>.</p>         
    </video></div>

    The CSS to make the cropping work is the following:

    .stage{
      width:400px;
      height:300px;
      position:relative;
    }
    video{
      width:400px;
      height:300px;
      position:absolute;
      top:0;
      left:0;
    }

    Absolutely positioned elements are taken out of the normal flow of the document. If you put an absolutely positioned element inside one that is relatively positioned, its top and left values are relative to the other element. In other words: the video now covers the stage completely.

    If we rotate the video we still have triangular spaces showing like in this example:

    Positioning a video absolutely in a relative container

    .demostage{
      width:400px;
      height:300px;
      position:relative;
    }
    .demovideo{
      position:absolute;
      top:0;
      left:0;
      -moz-transform:rotate(20deg);
      -webkit-transform:rotate(20deg);
      -o-transform:rotate(20deg);
      -ms-transform:rotate(20deg);
      transform:rotate(20deg);
      width:400px;
      height:300px;
    }

    To work around this, we must add a overflow:hidden to the stage DIV:

    Setting overflow:hidden on the stage hides the overlapping parts of the video

    .demostage{
      width:400px;
      height:300px;
      position:relative;
      overflow:hidden;
    }
    .demovideo{
      position:absolute;
      top:0;
      left:0;
      -moz-transform:rotate(20deg);
      -webkit-transform:rotate(20deg);
      -o-transform:rotate(20deg);
      -ms-transform:rotate(20deg);
      transform:rotate(20deg);
      width:400px;
      height:300px;
    }

    In order to provide a zoom and rotate functionality, we need to use JavaScript and buttons for the end user. The first hurdle here is – as you probably already realised from the CSS – browser differences in the syntax. Therefore we need to detect which of the transformations the current browser supports. The safest way is to ask the browser:

    var properties = ['transform', 'WebkitTransform', 'MozTransform',
                      'msTransform', 'OTransform'];
    var prop = properties[0];
    for(var i=0,j=properties.length;i<j;i++){
      if(typeof v.style[properties[i]] !== 'undefined'){
        prop = properties[i];
        break;
      }
    }

    Once this runs we can set a transformation with the following JavaScript syntax:

    var zoom = 1.5;
    var rotate = 20;
    v.style[prop]='rotate('+rotate+'deg) scale('+zoom+')';

    Of course it doesn’t make much sense to rotate the controls with the video. Therefore you need to provide your own. You can use any of the aforementioned players for that or roll your own. To demonstrate, I just built one with a single button allowing you to play and pause the video:

    The full source is available on GitHub, read the comments to see what is going on here.

    Just a quick example of what you can do with open technologies.