Can I add javascript dynamically to an existing script element

后端 未结 3 907
无人共我
无人共我 2020-12-06 00:54

I want to dynamically add javascript to an existing script element something like:

var se = document.createElement(\'script\');
se.setAttribute(\'type\', \'t         


        
3条回答
  •  鱼传尺愫
    2020-12-06 01:34

    All browsers currently support a javascript text property, and will evaluate the text when a new script element (without a src attribute) is added to the document.

    innerHTML or adding child nodes to a script element do not evaluate the script in all browsers.

    function addCode(code){
        var JS= document.createElement('script');
        JS.text= code;
        document.body.appendChild(JS);
    }
    

    //test case

    var s= 'document.body.ondblclick=function(e){\n'+
    'e=window.event? event.srcElement:e.target;\n'+
    'alert(e.id || e.tagName);\n'+
    '}\nalert("ready to double click!");';
    
    addCode(s);
    

提交回复
热议问题