Sunday, April 8, 2012

How are JavaScript host objects implemented?



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. :)



Source: Tips4all

1 comment:

  1. JS calls to DOM methods like getElementById cause the JS engine to call into the C++ code that implements the DOM. For example, in Firefox, the call ends up in nsDocument::GetElementById(const nsAString& aId, nsIDOMElement** aReturn).

    As you can see, Firefox maintains a hashtable that maps ids to elements in C++ as an optimization in this case, so it doesn't walk the whole DOM tree looking for the id.

    ReplyDelete