如何判断动态创建的元素何时呈现 [英] How to tell when a dynamically created element has rendered
问题描述
innerHTML
然后添加它使用 appendChild
到容器。 在这样做之后,在元素渲染之前有一个等待,可以读取 offsetWidth
,以了解文本的宽度。
目前,我正在使用 setTimeout(processText,100)
等待渲染完成。
有没有回调我可以听,或一个更可靠的方式来告诉我何时创建了一个元素?
目前没有DOM事件表示元素已经完全呈现(例如,附加的CSS应用和绘制)。这可以使一些DOM操作代码返回错误或随机的结果(例如获取元素的高度)。
使用setTimeout给浏览器一些开销用于渲染是最简单的办法。使用
setTimeout(function(){},0)
可能是最实际的准确性,因为它将您的代码放置在活动的浏览器事件队列的末尾,没有任何更多的延迟 - 换句话说,您的代码正好在渲染操作(以及当时发生的所有其他操作)。
I need to accurately measure the dimensions of text within my web app, which I am achieving by creating an element (with relevant CSS classes), setting its innerHTML
then adding it to the container using appendChild
.
After doing this, there is a wait before the element has been rendered and its offsetWidth
can be read to find out how wide the text is.
Currently, I'm using setTimeout(processText, 100)
to wait until the render is complete.
Is there any callback I can listen to, or a more reliable way of telling when an element I have created has been rendered?
There is currently no DOM event indicating that an element has been fully rendered (eg. attached CSS applied and drawn). This can make some DOM manipulation code return wrong or random results (like getting the height of an element).
Using setTimeout to give the browser some overhead for rendering is the simplest way. Using
setTimeout(function(){}, 0)
is perhaps the most practically accurate, as it puts your code at the end of the active browser event queue without any more delay - in other words your code is queued right after the render operation (and all other operations happening at the time).
这篇关于如何判断动态创建的元素何时呈现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!