Here’s a guest post from Konrad to convince you of the powers of Web Inspector! – Adam S.
Have you ever used that cool button on your BlackBerry® PlayBook™ tablet Browser that looks like a book? It’s the icon in the top left that enables Reader Mode. This is a neat feature which takes away all the advertisements and extraneous features from the page and shows you a clean summary of the content. Today I wanted to tell you about how this feature came to be, how we optimized its performance, and how it would not have been possible without BlackBerry® Web Inspector.
After adding some profiling information to the script, I discovered that most of the code was already relatively fast. However, after it had reloaded the page in a new WebView, it was doing its removal of the unwanted tags on the live DOM. This incurred a whole page request with sub-resources and content that we were going to be stripped out as soon as the page loaded.
Instead of incurring a page load, I did a deep copy of the DOM using
document.body.cloneNode(true), and then manipulated the HTML fragment off DOM. Finally I loaded the resulting HTML in a new WebView. The result of this change was an immediate gain in performance, reducing the amount of processing time from 45 seconds down to less than 5 seconds. But that wasn’t enough — no user should have to wait 5 seconds after hitting a button to see any results.
console.log(), they’re expensive. Instead, add your log message to a buffer and then print the results after the main processing is complete. The DOM was traversed several times during the algorithm’s run. We ended up using a TreeWalker instead of a for loop of
document.getElementsByTagName(“*”) being used. With these simple changes and further optimizations to the script, we further reduced the page processing time from 5 seconds down to under 1.5, which in and of itself is still a gain of over 300%.
So in summary, we went from 45 seconds down to less than 1.5 seconds — an astonishing 3000% performance boost that we could not have done without Web Inspector running on device.
- Add logs to your scripts for performance profiling, but buffer them and don’t print to console right away.
- Don’t reload the page when you don’t need to. If you want to modify the DOM, use HTML fragments.
- Profile individual methods and try different things. You’d be surprised how changing one line can make all the difference.