I was thinking about this today and I realized I don’t have a clear picture here.
Here are some statements I think to be true (please correct me if I’m wrong):
- the DOM is a collection of interfaces specified by W3C.
- when parsing HTML source code, the browser creates a DOM tree which has nodes that implement DOM interfaces.
- the ECMAScript spec has no reference of browser host objects (DOM, BOM, HTML5 APIs etc.).
- how the DOM is actually implemented depends on browser internals and is probably different among most of them.
- modern JS interpreters use JIT to improve the code performance and translate it to bytecode
I am curious about what happens behind the scenes when I call document.getElementById('foo'). Does the call get delegated to browser native code by the interpreter or does the browser have JS implementations of all host objects? Do you know about any optimizations they do in regard to this?
I read this overview of browser internals but it didn’t mention anything about this. I will look through the Chrome and FF source when I have time, but I thought about asking here first. 🙂
All of your bullet points are correct, except:
should be “…and translate it to native code”. SpiderMonkey (the JS engine in Firefox) worked as a bytecode interpreter for a long time before the current JS speed arms race.
On Mozilla’s JS-to-DOM bridge:
The host objects are typically implemented in C++, though there is an experiment underway to implement DOM in JS. So when a web page calls
document.getElementById('foo'), the actual work of retrieving the element by its ID is done in a C++ method, as hsivonen noted.The specific way the underlying C++ implementation gets called depends on the API and also changed over time (note that I’m not involved in the development, so might be wrong about some details, here’s a blog post by jst, who was actually involved in creating much of this code):
getElementById, perform the necessary parameter checks/conversions and route the call directly to a C++ method (nsDocument::GetElementById(const nsAString& aId, nsIDOMElement** aReturn))I’m fuzzy on details of the three last points in particular, so take it with a grain of salt.
The most recent improvements are listed as dependencies of bug 622298, but I don’t follow them closely.