remove appended script javascript

后端 未结 8 1675
执笔经年
执笔经年 2020-12-29 15:35

how can I remove my appended script because it causes some problems in my app.

This is my code to get my script

var nowDate = new Date().getTime();
v         


        
8条回答
  •  灰色年华
    2020-12-29 15:55

    Well,
    I got the same need, because of ajax calls triggered by event. Some calls being the earliest may return later, then overwriting document populated by the last call.

    removeChild(scriptEl) doesn't work. Changing src attribute doesn't work either.

    If jsonp is your only way out, and if you have control of the server response, you can let those appended to discriminate return on the callback.

    Just pass a timestamp parameter, then check it on the callback

    //callback
    function dummy(res, ts) {
     if(YAHOO.util.Selector.query('script[id='scriptIdPrefix+ts+']').length>0) {
         do your job
     } else {
         do nothing
     }
    }
    
    //add script
    var scriptIdPrefix='myScriptId';
    function ajaxCall() {
        var timestamp = new Date().getTime();
        var scriptId = scriptIdPrefix+timestamp;
        //remove the previous script el
        s=YAHOO.util.Selector.query('script[id^='+scriptIdPrefix+']');
        if(s.length>0) {
            document.body.removeChild(s[0]);
        }
        var script = document.createElement('SCRIPT');
        script.id = scriptId;
        script.type = 'text/javascript';
        script.src = 'http://server/notify.js&callback=dummy&ts='+timestamp;
        document.body.appendChild(script);
    
    }
    

    Assemble the result of the server notify.js accordingly:

    dummy([{"datax":"x","datay":"y"}], 1369838562792)
    

    In this way you will have just one script element like this with parametric id

    
    

提交回复
热议问题