Condividi tramite


Exploring IE9's Enhanced DOM Capabilities

For IE9 Platform Preview 4, we significantly re-architected how the Chakra JavaScript engine integrates into IE. This re-architecture, described in Dean’s post, subtly changes the programming model of the DOM for IE9 standards mode, making it consistent with new ECMAScript 5 capabilities, more interoperable with other browsers and aligned with emerging standards (WebIDL).

In this post I want to dive into the details of some of these programming model changes. You can take advantage of these enhanced DOM capabilities in the latest platform preview build. To highlight these changes, I’ll reference the Enhanced DOM Capabilities demo page that we released with the fourth Platform Preview.

All 24 puzzle pieces assembled into the image of the IE logo. This is a screenshot of IE9 running the Enhanced DOM capabilities demo at the IE Test Drive web page: https://ie.microsoft.com/testdrive/

That demo tests 24 capabilities that span 4 general categories:

  • DOM object inheritance from native JavaScript objects
  • JavaScript functional harmony with DOM objects
  • Interoperable programming features
  • New ECMAScript 5 support applied to DOM objects

The first two are closely related, so I’ll discuss them together:

DOM object inheritance from native JavaScript objects and JavaScript functional harmony with DOM objects.

Prior to IE9, the JavaScript engine was connected to the DOM via classic COM bindings. These legacy bindings allowed for only primitive object and function representations of the DOM to the JavaScript engine. Consequently, many basic JavaScript features that developers expected to be available to all objects and functions (including DOM objects like Window, Document, NodeList, etc.) were only available to native JavaScript objects (Array, Number, etc.).

The ECMAScript standard specifies basic operations that should work uniformly on all JavaScript objects, but allows “host objects” to deviate from those standard specifications. IE’s old JavaScript engine treated DOM objects as “host objects” which meant that basic JavaScript operations such as property access could behave oddly. While allowed by ECMAScript, inconsistent behavior between DOM objects and JavaScript objects created differences web developers had to account for.

For example, one common puzzler for many web developers was why IE DOM functions were reported as “object” to the typeof JavaScript operator rather than "function" (this capability is specifically checked in the demo as piece #10).

In IE9’s Standards Mode, we build our DOM as native JavaScript objects and functions rather than as “host objects,” thus enabling the features that web developers expect from native objects.

Interoperable programming features

The third group of capabilities showcase unique IE programming model behaviors that web developers commonly stumbled over. Because these behaviors were unique to the IE programming model, web developers found that their code didn't work the same across different browsers.

As part of our new integration architecture, we removed many of the inconsistencies that kept the same script from working the same way across browsers. The programming model changes may cause sites that have conditional code written for IE to behave differently in IE9 than it did before. Therefore, it is worthwhile describing these changes in more depth.

Functions now enumerated

In IE8 and before, enumerating a DOM object did not include any of that DOM object’s member functions. IE9 now enumerates any property on a DOM object that has its “enumerable” property descriptor value set to ‘true’. (In other words, enumeration can be programmatically altered.) Functions are now enumerated by default to be consistent with other browsers.

Removed implicit function invocation

DOM functions in previous versions of IE were quite special. Not only did they claim to be typeof “object”, but they also retained a static ‘this’ value which referred to the object to which they belonged. Consequently, it was possible to cache a reference to a DOM function, and invoke it without explicitly passing the ‘this’ value:

// Works in IE8 and earlier versions
// Doesn't work in IE9 or other browsers
var cachedGetElementById = document.getElementById;
cachedGetElementById('value');

In IE9, this now throws an exception, as it does in other browsers. Code that formerly depended on this IE behavior may use the “.call” workaround:

// Works in IE8/IE9 and other browsers
// Doesn't work in IE7 and earlier versions;
var cachedGetElementById = document.getElementById;
cachedGetElementById.call(document, 'value');

ECMAScript 5 provides a “bind” method for functions which allows them to take on the programming characteristics formerly supported by IE:

// Works natively in IE9 because of ECMAScript 5's 'bind' API
var cachedGetElementById = document.getElementById.bind(document);
cachedGetElementById('value');

Support for DOM exceptions and ‘const’ properties

The IE9 enhanced DOM now includes W3C-specified DOM exception objects and standardized error codes that web developers can use to determine (generally) the nature of a DOM API failure. These codes are commonly compared against well-defined 'const' properties to aid in code readability:


catch(ex) {
if (ex.code == DOMException.INDEX_SIZE_ERR)

}

The enhanced DOM provides the pre-defined 'const' properties as well as the architecture to throw and catch DOM exceptions.

Consistent toString behavior

With Chakra and the DOM fully integrated, the DOM does not have its own implementation of toString (a function that converts any object into a string form). While the old DOM’s toString implementation was similar to the JavaScript built-in version, it was not the same and often returned inconsistent or puzzling results. IE9 DOM objects now inherit and use the JavaScript built-in toString for more uniform results.

Separation of property and attribute storage

In the previous architecture, DOM objects had their own property storage. This property storage was the same as the storage location for attributes (those found in the HTML markup). With IE9's new architecture, an element’s attribute storage is now separate from the dynamic properties assigned to an element's script object. To illustrate this separation, consider the following example markup:

<div id="myId" class="c" user-defined-attribute="test">

In the above example, “id”, “class”, and “user-defined-attribute” are attributes. The div element's JavaScript object also exposes similar properties:

// Get the JavaScript object representing the body
var divOb = document.getElementById(‘myId’);
divOb.id; // "myId"
divOb.className; // "c"

These JavaScript properties retrieve the values stored in an element’s attribute list. For example, “id” retrieves the value of the “id” attribute. “className” retrieves the value of the “class” attribute.

In previous versions of IE, any dynamically-added properties would “magically” appear in the element’s attribute list and vice-versa due to the shared storage location. This could lead to unexpected results:

<div id="myId" class="c" user-defined-attribute="test">

var divOb = document.getElementById("myId");
// The next statement unexpectedly adds "userProperty" as
// an attribute to the element.
divOb.userProperty = "test"

// How many attributes?
alert("Total attributes = " + divOb.attributes.length);

IE9 and other browsers alert three total attributes ("id", "class", and "user-defined-attribute"), whereas previous versions of IE alert 4, adding "userProperty" to the list. The reverse example is more common—code that expects user-defined attributes to appear as dynamic properties:

<div id="myId" class="c" user-defined-attribute="test" userAttribute="test">

var divOb = document.getElementById("myId");
// Get the "userAttribute" and "user-defined-attribute" value
// (only worked in IE8 and previous versions)
var value1 = divOb.userAttribute;
var value2 = divOb["user-defined-attribute"];

We’ve seen a lot of code that expects this legacy IE behavior. The interoperable way to retrieve unknown attributes is to use “getAttribute,”

var value1 = divOb.getAttribute("userAttribute");
var value2 = divOb.getAttribute("user-defined-attribute");

and dynamic properties should not be queried through the attributes collection.

New ECMAScript 5 capabilities

In the last group of capability tests, new functionality provided by Chakra’s implementation of ECMAScript 5 is applied to the DOM. One of the primary goals for the enhanced DOM in IE9 was to provide a representation of the DOM that made logical sense within the context of the ECMAScript 5 language semantics. This was made much easier because one of the primary goals of ECMAScript 5 is to better support the functionality needed by DOM objects! In our implementation, we represented the DOM using as many native ECMAScript 5 language features as possible, including extensive use of accessor (getter/setter) properties.

This native integration allows all of the new ECMAScript5 features to work equally well with native objects as with DOM objects.

The enhanced DOM capabilities demo shows only 24 samples of what is possible when the DOM is fully integrated with an ECMAScript 5-capable JavaScript engine like Chakra. We are very excited about this support in IE9 and want to help get better interoperability for ECMAScript language bindings across browsers. An important step is standardizing these binding within the W3C, and we’re happy to contribute to that effort.

W3C web standards have always supplied a language binding for ECMAScript implementations as a way to translate the standard IDL (Interface Definition Language) into JavaScript objects. However, these bindings lacked sufficient detail to create much more than a simple “host object” binding (a binding without consideration of the full spectrum of ECMAScript language features). While other browsers have a much more comprehensive language binding than simply “host objects,” integration inconsistencies remain. These inconsistencies can really frustrate JavaScript framework developers who wish to write abstraction layers and features on top of the basic language support. The need for consistency led to a proposed standard called WebIDL (Web Interface Definition Language). The WebIDL specification describes in much more precise detail, how to translate a given W3C spec written using WebIDL into JavaScript objects.

In a follow-up post, I will describe in more detail how we used WebIDL to inform and guide the development of the IE9 enhanced DOM.

Please testdrive the IE9 enhanced DOM. We look forward to your comments and feedback.

Travis Leithead
IE Program Manager

Comments

  • Anonymous
    September 02, 2010
    The comment has been removed

  • Anonymous
    September 02, 2010
    Rant more, noob. That's sure to get you the attention you crave.

  • Anonymous
    September 02, 2010
    "IE9 and other browsers"

  • Point was "differenciation" some years ago.
  • Point now is "Being similar"... It's good though. Anyway, it looks like IE is doing more and more standard stuff and get closer and closer to Chrome and Firefox. Hope u're going to make it easier for webdevs... This kind of stuff makes me scared: "// Works in IE8 and earlier versions // Doesn't work in IE9 or other browsers " It's good that you force webdev to be more compatible with other browsers. But u forced them to support IE specifically ( as IE always had its own way of support ) and now u force them to undo it. Find it unfair. But let's see the final result. Nicolas.
  • Anonymous
    September 02, 2010
    Please MS, throw IE engine and adopt WebKit. It's less expensive for you, and it's great for us!

  • Anonymous
    September 02, 2010
    @Luke >> Please, Luke, throw your comments away and adopt a brain.

  • Anonymous
    September 02, 2010
    @Aethec >> I laughed a lot and I totally agree with you

  • Anonymous
    September 02, 2010
    Randall you are aware that the behaviour of innerHTML in IE is documented and also that innerHTML is not part of a standard and will never be, aren't you? Basically MS can claim that innerHTML behaves accoridng to specification because they invented it and documented it this way and all other browsers implemented it in a different way. Oh and BTW I agree that the behaviour (I assume you are talking about the bugs with tables and so on) should be changed.

  • Anonymous
    September 02, 2010
    @Bored - the problem is that it might be yet another rant but the point of the rant still remains.  Microsoft has been bashed on their lack of support for DOM access and manipulation methods since they first came out for IE6 (or was it even before that?) The API that developers use to interact with the DOM, style & positioning of their content IS the #1 concern of developers because if they can't do it properly/easily their own designs and development take a hit. The API in IE has changed little over the past decade stagnating with dozens and dozens of issues, broken implementations and missing features. Over 50% of the methods in the DOM Level 1 implementation in IE (a W3 spec since 1998!) had a bug or missing implementation in it for the past 10 years! www.w3.org/.../ecma-script-language-binding.html That's not a minor issue - that's a complete mess for developers that are expecting things to just work because the specs are perfectly clear and simple. Why did we have to wait until IE8 to get getElementById() to work correctly? This method is FUNDAMENTAL to DOM manipulation. Developers are very aware of the innerHTML getter/setter in JavaScript - what they don't get is why it works flawlessly in Chrome, Firefox, Safari & Opera - yet IE STILL hasn't fixed it to work on all elements yet. I feel sorry for Comp Sci students that graduate today thinking they can build awesome web applications in Firefox & Chrome (and they do) only to find out that IE can't support their content because of 10 year old bugs that haven't been fixed yet. Sad Panda, say hello to Fail Whale.

  • Anonymous
    September 02, 2010
    @Stilgar - documenting that your implementation is flawed and horribly broken doesn't help anyone. and you are wrong - innerHTML is a standard, and always will be: dev.w3.org/.../Overview.html More importantly it was adopted by all browsers years ago - the only difference is that all the other browsers implemented it correctly. Only IE has sat for 10 years on their implementation unwilling to even discuss fixing it. Its pretty disgraceful if you ask me.

  • Anonymous
    September 02, 2010
    Hmm I'm surprised. Did they add it in HTML 5? Thanks for correcting me.

  • Anonymous
    September 02, 2010
    The comment has been removed

  • Anonymous
    September 02, 2010
    Just another reminder: HTML5 Forms, CSS3 Transitions, Gradients, Text Shadow, Multi-Column, and more. CSS3 features is more important than Canvas and SVG's. Some sites (HTML5/CSS3) don't render correctly on IE9 previews.

  • Anonymous
    September 02, 2010
    Does anybody know something about webworkers and websockets?

  • Anonymous
    September 02, 2010
    @david Yeah don't improve what you have, keep everyone on aging browsers like IE6,7 and soon 8! /sarcasm Seriously, it has already been mentioned enough times that Microsoft has 'misbehaved' in the past when it concerned standards support. No need to go and repost it each and every time... Besides you're barking up the wrong tree, go and email the companies that are still using IE6 that they should upgrade. IE9 will be a big step up and in a lot of ways a step ahead of other browsers. I hope the remaining issues that people discover and dilligently post here in the comments and/or connect will be looked at and fixed when RTM hits. Keep up the good work guys, you're doing great! (and don't stop when IE9 is out!)

  • Anonymous
    September 02, 2010
    @MacGyver - "IE9 will be a big step up and in a lot of ways a step ahead of other browsers. " But not in most ways. IE9 will be behind all other browsers overall and it won't even be out till next year. In the meantime, the other more modern browsers are moving ahead of Microsoft's fixed target of today's implementations. IE will always be the last place finisher.

  • Anonymous
    September 02, 2010
    <<innerHTML is a standard, and always will be>> Citing an unfinished draft of a spec that isn't even in the final stages of authoring either is an attempt to mislead, or an indication of ignorance. <<Why did we have to wait until IE8 to get getElementById() to work correctly>> If you wrote your code properly, IE5, 6, and 7 worked just fine with getElementById(). The fact that it also accepted incorrect case-insensitive syntax to accommodate incorrectly authored pages is an interesting footnote, but to imply that it didn't work is, again, either an attempt to mislead, or an indication of ignorance. <<Does anybody know something about webworkers and websockets?>> Everyone knows something about these proposed features. IE9 doesn't support them, if that's what you mean to ask. << Microsoft's fixed target of today's implementations>> You demonstrate that you don't really understand much at all about the software business. <<CSS3 features is more important than Canvas and SVG's>> Says you. I hope that no one is stupid enough to engage in the obvious and pointless debate. <<I feel sorry for Comp Sci students that graduate today >> And I feel sorry for CompSci students that graduate and end up doing a job that doesn't require anything they learned in school, one that requires knowledge of only simple technologies that any middle-school kid can master.

  • Anonymous
    September 03, 2010
    Anyone know why the Enhanced DOM Capabilities demo fails entirely in Firefox 4 Beta 4?

  • Anonymous
    September 03, 2010
    Please make IE layout, design & UI as fast as its js-engine. Also any updates on Addons for IE? Can we have some quality Addons just like other browsers have?

  • Anonymous
    September 03, 2010
    But not in most ways. IE9 will be behind all other browsers overall and it won't even be out till next year. In the meantime, the other more modern browsers are moving ahead of Microsoft's fixed target of today's implementations. IE will always be the last place finisher.

  • Anonymous
    September 03, 2010
    Pues creo que esto del estilo minimalista a sido copiado de google chrome, y por ahora sigo fiel a chrome, basta ver si IE9 es mejos, promete ser mejor, por ahora esperar y ver si ya cumple con los estandares de acid3.

  • Anonymous
    September 03, 2010
    The comment has been removed

  • Anonymous
    September 04, 2010
    The comment has been removed

  • Anonymous
    September 04, 2010
    I've got a JavaScript related question, so I've built this drag and drop script and IE8/7/6 absolutely refuse to acknowledge a variable (dragged_z) regardless of it's scope/position in the code/etc. A full working HTML file (in text) with the issue is here and it has great backwards compatibility... www.dynamicdrive.com/.../showthread.php It works great in IE9 though I don't understand why it doesn't see the variable (using typeof IE8 says it's undefined) and this is the first time I've ever had IE see one variable though not another.

  • Anonymous
    September 04, 2010
    What does "refuse to acknowledge a variable" and "doesn't see the variable" mean? Might you restate your problem in technical terms? Your page works fine for me in IE9, despite the fact that you fail to define your "z" variable.

  • Anonymous
    September 04, 2010
    The comment has been removed

  • Anonymous
    September 04, 2010
    jab, you should probably read your own code. "z" is a different variable than "dragged_z".

  • Anonymous
    September 04, 2010
    @Matt yeah that was a different file, back-tracking led me to currentStyle not being written correctly. I posted the working code and it works great in IE 5.5+, Opera 7.5+, etc. Thanks! www.dynamicdrive.com/.../showthread.php

  • Anonymous
    September 04, 2010
    The history of IE is terrible. They said they were trying to do things by the standards last time and look at it now. IE8 is an awful browser and IE9 will be behind technology again when it releases. They've recoded their browser so many times. It makes you under what rubbish will be under the hood this time.

  • Anonymous
    September 05, 2010
    The history of trolls is terrible. They say they are not trolls but look at them. Whining and complaining and shaking their little fists at the world and the happy people around them. They've contradicted themselves with their lies so many times that they're dizzy with confusion. It makes you wonder what rubbish they will next make up for IE9 which looks like an extemely promising browser.

  • Anonymous
    September 05, 2010
    The comment has been removed

  • Anonymous
    September 05, 2010
    The history of msbasher trolls is terrible. They come to the IEBlog and whine and complain and moan and lie and fabricate and attack and belittle and lie some more. Sometimes they are mercifully brief but persistent while other times they author long-winded tirades which, much like a traffic accident, attract rubberneckers who cannot help but watch. The wasted time (on the part of the troll, and the thousands of innocent victims) is a tremendous loss to society, a toxic poison that drags the life out of what should be a vibrant community. It's simply terrible.

  • Anonymous
    September 05, 2010
    We'll stop if the msfanboys stop.  Our only intention is to improve IE, give attention to the bugs that need fixing most and indicate our displeasure at the lack of transparency that was promised to us back when Dave Massy was Program Manager of IE. - Yes we miss his honesty. We've asked repeatedly for details of the expected timeline for bug fixes for well documented, long standing bugs in IE that hamper our development. If you have an issue with us asking for answers that's your problem - go troll elsewhere. We just want the facts. I think waiting 10 years for a fix is a bit much. Extend an olive branch to developers and give us an idea of when we can expect these fixes - thats all we are asking for.

  • Anonymous
    September 05, 2010
    The comment has been removed

  • Anonymous
    September 05, 2010
    IE9 is going to be the best browser in the world. IE8 running in Protected Mode in Windows 7/Vista is the most secure browser in the world. IE9 will add huge performance boost and great UI enhancements to make it the greatest web browser fo all time. Just like Windows 7 is the greatest operating system in the history of computing.

  • Anonymous
    September 06, 2010
    Sam, he didn't say innerHTML was "in" a spec. In the same vein, your statement that "specs that are in progress are just as important as specs that have met final approval" betrays your significant ignorance of the standardization process. Given that you're clearly not an actual web developer, and given that no one has yet to put forth a clear test suite and a clear bug to consider voting for on Connect, I would be entirely astonished if the IE team bothered to make any changes here at all. It's not as if they bother to read the comments on the blog posts here, given that the Value-To-Troll ratio is so low. Apple, Massey never promised transparency, and if you look at the blog posts of that era vs. those of this, there is FAR more information in the blog posts of today. Trolling here isn't going to get you any answers. It's pretty obvious that the value of engaging with trolls in blog comments is so low that it's not worth msfts time. Go back and read the blog post about why they're using connect instead of some other system. They're desperately trying to increase the Value-To-Troll ratio so that they can actually benefit from their community, which is the largest of any browser.

  • Anonymous
    September 06, 2010
    @Weary - wow! way to play the Troll! Where to start - A spec is a spec it doesn't matter if it is complete or not when it is a W3C spec on the way to becomming complete. IE has many, many innerHTML bugs - there is no need to file them in Connect as they've been well publicized since they the day IE6 hit the Internet. If you seriously don't know what they are, you have never used innerHTML in your development or you haven't learned how to Google. The Value-To-Troll ratio on this blog is fine, and certainly much better than the BugSubmission-To-MSFTPayingAttention factor. Sorry Weary, "Transparency" is EXACTLY what Massy (no e) promised and during the videos, comments, chats and his own blog - he actually delivered. I personally had conversations with him where he was very transparent about the state of IE's bugs and the teams focus on the most glaring user-facing issues first. As for Connect - it was a major failure. If MSFT had kept up with the bug submissions, ported them properly from release to release, and provided a decent search mechanism for the site then it might have been useful. Unfortunately Connect is now dead (yeah it still exists but real developers have given up submitting bugs since they get no validation, no attention, no commitment, no ETA for a fix, and most disgustingly get closed with "By Design".) - yet another case of the big guy seriously not getting what public bug tracking is all about. "Closed - Design to be improved in another release" would be so much better than an arogant attempt at indicating the current design is flawed and needs improvement. IE does have the largest browser market share - correct! I wonder if that has anything to do with tying the browser to the operating system and shipping it with Windows? These days IT departments realize their users want control and a decent browser and either install Firefox & Chrome or give users the chance to. Like many people the first thing I do with a new Windows install is open IE and go to http://www.GetFirefox.com/ within a minute my web browsing experience improves 10 fold. Thanks for your ms-troll comments @Weary, your dedication to not knowing the facts you were posting about was a new classic low - well done.

  • Anonymous
    September 09, 2010
    I don't ever think that ie will be the safest browser... It gets too targeted, no use. But in the other hand comes with the less bugs in browsing. I guess you have to chose your browser depending on the level of security that you want to have

  • Anonymous
    September 09, 2010
    The comment has been removed