Alternatives to [removed]

前端 未结 4 1421
囚心锁ツ
囚心锁ツ 2020-12-20 03:24

I am in a situation where it seems that I must use document.write in a javascript library. The script must know the width of the area where the script is defined. However, t

4条回答
  •  温柔的废话
    2020-12-20 03:57

    This just occurred to me, and I remembered your question: the script code can find the script block it is in, so you can traverse the DOM from there. The current script block will be the last one in the DOM at the moment (the DOM still being parsed when the code runs).

    By locating the current script block, you can find its parent element, and add new elements anywhere:

    
    
        
            
        
        
            
            
    before script block after script block

    http://jsfiddle.net/gFyK9/2/

    Note the "blue text" span will be inserted before the "after script block" span. That's because the "after" span does not exist in the DOM at the moment appendChild is called.


    However there's a very simple way to make this fail.

提交回复
热议问题