开发者

Horrible performance when removing HTML element from UIWebView

I'm currently writing an iOS app that uses a UIWebView for surfing around pages. Sometimes I ne开发者_运维知识库ed to dynamically remove elements in the UIWebView using stringByEvaluatingJavaScriptFromString:, but this locks up the main UI for sometimes up to 2 seconds on my first gen iPod touch, and maybe half a second on an iPhone 3GS. The JavaScript I'm using to remove it by is simply:

element.parentNode.removeChild(element);

Nothing more complicated than that. At the same time I'm doing some very basic 2D rendering in OpenGL ES, and if rerendering the UIWebView wouldn't lock up I would use just simple CoreAnimation on the main thread. Could it be that it has to recalculate the DOM tree, all element positions etc? Should this really lock up the main UI thread? Is it that I'm calling stringByEvaluatingJavaScriptFromString: that locks up everything? Is this normal and to be expected on this kind of hardware? The odd thing is it is able to render some semi-complex MooTools animations in the webview, with opacity and height changes, but removing one single element takes several seconds.

Does anyone have any ideas in improvements? Maybe just hiding elements using visibility: hidden is better, or setting opacity: 0? Any thoughs or wise words of experience?


DOM tree manipulations are horribly slow in all browsers, especially iOS Safari. The key factor is size of the DOM tree. Because of this, the best advice is to delete as you go (don't use visibility:hidden).

If you can possibly avoid using direct dom manipulation and instead use setInnerHTML(), this will yeild much better performance. I've seen it work in the order of 100 times faster. It is counter-intuitive, but doing a whole lot of string manipulation and then throwing a string at the browser is much faster. This is because browsers are optimised to render DOM trees from strings.

In your case setInnerHTML might only be helpful if you are trying to delete a number of nodes at the same time. If you are only deleting one node, you're stuck - just try to keep the DOM small.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜