remove appended script javascript

2019-03-16 19:48发布

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();
var url = val.redirect_uri + "notify.js?nocache=" + nowDate + "&callback=dummy";
var script = document.createElement('script');
script.src = url;
document.body.appendChild(script);

Then I have an auto load function, that causes to create another element script.

I want to get rid of the previous element that was appended before another element is added.

7条回答
SAY GOODBYE
2楼-- · 2019-03-16 20:02

Basically you can remove script tag by using a function similar to this one:

function removeJS(filename){
 var tags = document.getElementsByTagName('script');
 for (var i = tags.length; i >= 0; i--){ //search backwards within nodelist for matching elements to remove
  if (tags[i] && tags[i].getAttribute('src') != null && tags[i].getAttribute('src').indexOf(filename) != -1)
   tags[i].parentNode.removeChild(tags[i]); //remove element by calling parentNode.removeChild()
 }
}

Note, it use filename parameter to identify target script to remove. Also please note that target script could be already executed at the time you're trying to remove it.

查看更多
再贱就再见
3楼-- · 2019-03-16 20:07

What you can do is remove the script immediately after it has been loaded:

var nowDate = new Date().getTime();
var url = val.redirect_uri + "notify.js?nocache=" + nowDate + "&callback=dummy";
var script = document.createElement('script');
script.src = url;
script.onload = function( evt ) {
    document.body.removeChild ( this );
}
document.body.appendChild(script);

Anyway I think it is a better idea to append the script to the header (where all the other scripts reside) than to the body.

查看更多
你好瞎i
4楼-- · 2019-03-16 20:08
var flag1=0,flag2=0;
$(window).resize(function(){
    if ($(window).width() < 480){
        flag1++;
        console.log(flag1);
        flag2=0;  
    }
    else 
        if($(window).width() > 480){
            flag2++;
            console.log(flag2);
            flag1=0;
        }   
    if(flag1==1){
        $("body").append("<script class='abc' src='custom.js'/>");
    }
    else
        if(flag2==1){
            $(".abc").remove();
        }
});
查看更多
乱世女痞
5楼-- · 2019-03-16 20:19

I would simply check to see if you've already added the script. Adding it and then removing is adds unnecessary complexity. Something like this should work:

var scriptAdded = false;

if(scriptAdded == false) {
    document.body.appendChild(script);
    scriptAdded = true;
}
查看更多
Luminary・发光体
6楼-- · 2019-03-16 20:20

In case of JSONP and your use of jQuery, why not take full advantage of jQuery's JSONP loading facilities, which do the post-clean-up for you? Loading JSONP resource like this, doesn't leave a trace in the DOM:

$.ajax({ url: 'http://example.com/', dataType: 'jsonp' })

The <script> tag used for loading is removed instantly as soon it's loaded. If the loading is a success. On the other hand, failed requests don't get cleared automatically and you have to do that yourself with something like this:

$('head script[src*="callback="]').remove();

called at the right time. It removes all pending JSONP <script> tags.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-03-16 20:20

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

<script id="myScriptId1369838562792" type="text/javascript"  
src="http://server/notify.js?callback=dummy&ts=1369838562792"></script>
查看更多
登录 后发表回答