How to remove already generated script tag and re-generate?

感情迁移 提交于 2019-12-06 10:09:55
JDev

Well you can give id to script tag when you are adding dynamically.

var script   = document.createElement("script");
script.setAttribute('id', 'addedScript');
script.type  = "text/javascript";
script.text  = "window.twttr = (function (d,s,id) {var t, js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) return; js=d.createElement(s); js.id=id;js.src=\"//platform.twitter.com/widgets.js\"; fjs.parentNode.insertBefore(js, fjs);return window.twttr || (t = { _e: [], ready: function(f){ t._e.push(f) } });}(document, \"script\", \"twitter-wjs\"));(function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return;js = d.createElement(s); js.id = id; js.src = \"//connect.facebook.net/en_GB/all.js#xfbml=1\"; fjs.parentNode.insertBefore(js, fjs);}(document, \"script\", \"facebook-jssdk\"));var script_generated=1";
// use this for inline script
document.body.appendChild(script);

After that you can check if script tag exists by using this and remove using .remove() query function.

if(addedScript != undefined) {
  $("#addedScript").remove();
} 

Hi you can get the reference object for that script tag and you can change the referenced src file using object.

It should be like this,

var $jsRef = $('<script type="text/javascript" >').appendTo(document.body);
$jsRef.attr("src","jsFileName.js");

// You can also add content like this
$jsRef.append(content);


// You can change the js file name or content the same way
$jsRef.attr("src","newJSFileName.js");

// Changing the content like this
$jsRef.empty();
$jsRef.append(content);

ALternatively you can set the id for script tag and change the content based on the id instead of accessing with objects.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!