Friday, May 11, 2012

JavaScript Caching: appendChild vs document.write

I found myself trying to prefetch some data which would appear in an iframe. I wanted to see if requesting the same JSON in the parent page and then in the iframe would cause the second request, made in the iframe, to hit the browser's cache in all cases. It turns out that for Internet Explorer and Web Kit based browsers it depends on how you request the JSON in the parent page.

If you use appendChild in IE the identical JS request will hit the browser cache.
If you use document.write in IE it will not hit the cache.

However, in Chrome and Safari if you appendChild in the parent, you will miss the cache. Using document.write in the parent page causes a cache hit.

Here are the results I gathered.
Cache Hit? both document.write parent document.write
iframe appendChild
parent appendChild
iframe document.write
both appendChild
Internet Explorer miss miss hit hit
Firefox hit hit hit hit
Chrome hit hit miss miss
Safari hit hit miss miss
Opera hit hit hit hit
Android ? ? ? ?
iOS ? ? ? ?

All versions of IE behaved the same, I didn't check different versions of the other browsers.

To test this I wrote a test web application called json-caching-exploration. It's a simple web app that runs on App Engine.

Server and HTML
JavaScript

I haven't run this against mobile browsers yet. If you give it a try please let me know what you find.

It's a shame that these browsers behave differently, especially given the differences in browser behavior between loading JavaScript using document.write and appendChild.