How to tell when a dynamically created element has rendered

前端 未结 7 1590
我在风中等你
我在风中等你 2020-12-02 12:54

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

7条回答
  •  不知归路
    2020-12-02 13:17

    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).

提交回复
热议问题