Friday, November 11, 2011

Javascript: Maximum call stack size exceeded in Chrome

jQuery templates is very powerful mechanism of building client side rendering logic. But large templates are very expensive in terms of browser resources and not all browsers can deal with it. It was unexpected, but the most modern browser with the best javascript engine V8 - Google Chrome (I used version 16) failed to render large template.

The task was pretty straightforward - build html table with around 400 rows and 35 columns through jQuery templates. The table is quite big and probably it’s not the best UX to show such table to the user, but it is what it is. IE8/9, Firefox 7+ rendered everything perfectly, but then I checked Google Chrome and it failed with throwing the following error: RangeError: Maximum call stack size exceeded.

After very deep debugging of jQuery templates and jQuery I figured out the problem. jQuery templates library builds array of strings and then prepares nodes to insert them to the DOM. On large templates the resulting array is really big - in my case around 100k+ items. jQuery templates uses jQuery.map method which calls the following method in the end:

// Flatten any nested arrays
return ret.concat.apply( [], ret );

IE8/9 and Firefox process this amount of data absolutely fine, but Google Chrome - not. I prepared small script in jsfiddle and it looks Chrome cannot process even 70k items:


As a recommendation how to avoid this issue could be not having such number of items passed into the template or generate each item individually and insert it to the DOM - this will not create huge arrays and will work completely fine in all browsers.

1 comment: