This blog series has sailed from the shores of networking, passed down waterfalls and reflows, and arrived in ECMAScriptland. Now, turns out there’s one bridge to cross to get to DOMlandia.
(OK, I need to get some sleep, evidently. Anyway.) Ara Pehlivanian talked about strategies for loading JavaScript code. Yesterday’s post was about rendering and how you can prevent making things worse in JavaScript. Today’s post will be about DOM access optimizations and, if all is good, tomorrow’s post will round up the JavaScript discussion with some techniques for extreme optimization.
Document Object Model (DOM) is a language-independent API for accessing and working with a document. Could be an HTML document, or XML, SVG and so on. DOM is not ECMAScript. ECMAScript is just one way to work with the DOM API. They both started in the web browser but now things are different. ECMAscript has many other uses and so has the DOM. You can generate a page server side, using the DOM is you like. Or script Photoshop with ECMAScript.
All that goes to show that ECMAScript and DOM are now separate, they make sense on their own, they don’t need each other. And they are kept separate by the browsers.
For example WebCore is the layout, rendering and DOM library used by WebKit, while JavaScriptCore (most recently rewritten as SquirrelFish) is the implementation of ECMAScript. In IE – Trident (DOM) and JScript. In Firefox – Gecko (DOM) and SpiderMonkey (ECMAScript).
An excellent analogy I heard in this video from John Hrvatin of MSIE is that we can think of the DOM as a piece of land and JavaScript/ECMAScript as another piece of land. Both connected via a toll bridge. I tried to illustrate this analogy here.
All your JavaScript code that doesn’t require a page – code such as loops, ifs, variables and a handful of built-in functions and objects – lives in ECMALand. Anything that starts with document.* lives in DOMLand. When your JavaScript needs to access the DOM, you need to cross that bridge to DOMlandia. And the bad part is that it’s a toll bridge and you have to pay a fee every time you cross. So, the more you cross that bridge, the more you pay your performance toll.
So, how serious is that performance penalty? Pretty serious actually. DOM access and manipulations is probably the most expensive activity you do in your JavaScript, followed by layouting (reflowing and painting activities). When you look for problems in your JavaScript (you use a profile instead of shooting in the dark, of course, but still) most likely it’s the DOM that’s slowing you down.
This code is bad because it touches the DOM twice on every loop tick. It doesn’t cache the reference to the DOM element, it looks for that element every time. Then this code also updates the live DOM which means it causes a reflow and a repaint (which are probably buffered by the browsers and executed in batches, but still bad).
Now obviously this is a bad and made up example, but it does show the magnitude of the problem with DOM access.
How to speed up DOM access? Simply do less of it. If you have a lot of work to do with the DOM, cache references to DOM elements so you don’t have to query the DOM tree every time to find them. Cache the values of the DOM properties if you’ll do a chunk of of work with them. And by cache I mean simply assign them to local variables. Use selectors API where available instead of crawling the DOM yourself (upgrade your JavaScript library if it’s not taking advantage of the selectors API). Be careful with HTML Collections.
Basically, every time you find you’re accessing some property or object repeatedly, assign it to a local variable and work with that local variable.
The special thing about them is that they are live queries against the underlying document. And they get re-run a lot, for example when you loop though the collection and access its length. The fact that you touch the length requires re-querying of the document so that the most up-to-date information is returned to you.
The slower version requeries the document, the faster doesn’t because we use the local value for the length. How slower is the slower? Depends on the document and how many divs in it, but in my tests anywhere between 2 times slower (Safari) to 200 times slower (IE7)
Another thing you can do (especially if you’ll loop the collection a few times) is to copy the collection into an array beforehand. Accessing the array elements will be significantly faster than accessing the DOM elements in the collection, again 2 to 200 times faster.
If you do that you also need to account for the one-off cost of copying that collection to an array.
Event delegation is when you attach event listener to a parent element and it handles all the events for the children because of the so-called event bubbling It’s a graceful way to relieve the browser from a lot of extra work. The benefits:
You will usually use fewer functions to handle the events because you’re attaching one function to handle parent events, not individual function for each child element. This means less functions to store in memory and keep track of.
Easier to detach event handlers when an element is removed and therefore easier to prevenk IE memory leaks. Sometimes you don’t even need to detach the event handler if children change, but the event-handling parent stays the same.
The United States and Mexico announced plans last week to team up in the fight against tuberculosis, the San Diego Union-Tribune reports. The binational effort includes a $16 million grant over six years to Mexico from the U.S. Agency for International Development. The monies will be used to expand treatment and testing efforts in 13 Mexican states, including six border states. Mexico also is planning to better monitor its patients, particularly for new infections, ensure continuation of treatment and improve training of laboratory personnel to diagnose TB. Although the lung disease is "quite curable," TB becomes resistant to drugs when the six-month treatment is interrupted -- a common occurrence for those crossing international borders. "It's not expensive to treat TB unless you fail in doing it right the first time," Dr. W. Reynolds Archer, the Texas commissioner of health, said. One-third of the world's population is infected with the TB bacterium, but only 10% will become sick and contagious, resulting in 8 million new cases each year. Global Health Council President Dr. Nils Daulaire warned, "What's looming is a global health problem. We need collaboration between countries, and we have to act quickly before the drug resistance spreads" (Duerksen, 3/5).
Jaime Sicairos has served as Pastor of Calvary Road Baptist Church since June 17, 2012. He is a graduate of Truth Baptist Bible College. Pastor Sicairos has been married to Elizabeth Sicairos for 15 years. They have four children Nicholas, Connor, Jameson and Sienna. Read More
If you’re looking for a fun, personal and relaxed photographic experience, you have come to the right place! Caroline Ann Photography is a Cambridgeshire-based Family and Children’s photographer that offers a full service starting with a consultation to design your session and concluding with your special Reveal Night. This is when you get to see all your images for the first time and have Caroline’s help in choosing and designing your wall art or keepsakes. In between she is on hand to help coordinate outfits, to recommend hair stylists and make-up artists (if wanted), and to surprise you with a few treats and premium personal service along the way. Although the company is based in Cambridge it also serves Norfolk, Hertfordshire, Bedfordshire and the London areas.
Caroline Ann Photography can help you with your wedding photography creating wonderful memories which also includes an optional complementary engagement shoot. They run workshops for parents and grandparents who want to know how to take better pictures of their family in a simple but fun way. Caroline Ann Photography runs various family packages including: Seed to Sprout, Family and Children photography packages – for people who value beautiful, quality photography.
Caroline would love to show you her work as it’s the best way to find out more about her as a photographer. Grab a cup of coffee and choose a gallery that peeks your interest!
Scamp Theatre’s delightful adaptation of Julia Donaldson and Axel Scheffler’s Stick Man features a trio of top actors and is packed full of puppetry, songs, live music and funky moves.It’s suitable for all aged 3+ but all ages are welcome. Go on book it up – you’ll have more fun than you can shake a stick at (boom boom!)
Jessica Fostekew is headlining this month’s comedy tent at the magical Willow Tree. Joining her is Birmingham based Freddie Farell, Fiona Rirdgewell (semi-finalist in Funny Women 2015, and a Golden Jester Finalist in the same year), Lovdev Barpaga and MC Chris Norton Walker. Enjoy a late summer’s evening of giggles & drinks in deck chairs with twinkling lights & fire pits.
Banish the back-to-school blues and enjoy an evening of classic cinema with the family. The Fitzwilliam Museum have joined forces with pop-up cinema company Venture Cinema to bring you Disney’s classic animated version of The Jungle Book on the big screen. So bring a blanket, pack some snacks and gather on the Museum’s lawn for some old-school entertainment.
Who can forget nobody puts Baby in a corner! Baby is back along with the gorgeous Leonardo DiCaprio and the heart-wrenching Moonlight (not in that order) and they’re all hanging out at the enchanted Orchard Tea Gardens in Grantchester. This isn’t your usual cinema experience – expect live music before the film, deckchairs under the trees of The Orchards draped in lights, street food, an independent pop-up bar, vintage popcorn machines, blankets – pretty cool hey!
It’s a first and is eagerly awaited – the inaugural Cambridge Home and Garden Show. This brand new event is dedicated to home and garden design and will feature a full exhibition hall, talks and demos, a pop up café and free professional design consultations. This free event is open to the public all day but you will need to register online for a ticket in advance.
This festival is one for all the family celebrating all things outdoors and all things local with great live music, delicious street food, local craft beer, lovely artisan stalls and an awesome kids zone.
The Riverside Park will be lit up with action this Sat as it transforms into an outdoor cinema for the afternoon/evening. The fun kicks off at 4pm with Peppa Pig (U) for the littl’uns, 5.15pm see Beauty and The Beast (PG) appear followed by Labyrinth (PG) at 8pm for those allowed to stay up later. Bring your own blankets, chairs, food and wine but Ambience Cafe will stay open, as well as Mobi Pizzeria, popcorn from Cineworld, sweets from Sweet Paradise and the healthy fruit stall from The Tesco Community Team. Better still the event is free to attend.
Didn’t make the Fringe? Me neither, but don’t panic Tom Slade, the Canadian renowned for his carefree attitude and broad-minded vision has hot-footed it direct from the Edinburgh Festival. You might have seen Tom on BBC One’s Live at the Apollo, Michael McIntyre’s Comedy Roadshow, The John Bishop Show and Ch4’s Comedy Galato so we’re talking to a pro on the comedy scene where nothing is taboo.
Jeremy Vine is known to us all for his coverage for BBC Elections, for presenting BBC Two’s Eggheads, and perhaps most of all the for the Radio 2 show he has presented since 2003, a show that attracts more than seven million listeners. What My Listeners Say is a book punctuated by vivid anecdotes and laugh-out-loud moments as Jeremy explains what it’s like to hit a button and hear, unvarnished and unspun, the voices of so-called ordinary people – and why they are not so ordinary after all. Jeremy tells all in this hilarious and thought-provoking memoir of his life, his Radio 2 listeners and his appearance on Strictly Come Dancing.