javascript – 更改页面源参考文件路径

我有一个应用程序,它引用了一个javascript文件。 长话短说,对于很多原因,我不能改变这个js文件,也不能改变它被引用的地方。 所以我想使用javsacript将参考文件路径更改为我的文件。

即:在我的应用程序中,我在页面的末尾有一个引用,如:

 

我无法更改此文件的引用路径,也无法更改此文件的内容。

但我有另一个js文件加载在页面顶部

   

我想在我的fullControl文件中编写一个Snippet来更改引用路径

  

我试过document.querySelectorAll('script')document.find('script')但是这没有帮助。 需要任何指针

也许,您可以尝试使用jquery的holdready函数,如下所示

 $.holdReady( true ); $.getScript( "myplugin.js", function() { $.holdReady( false ); }); 

那么你必须寻找包含属性src的脚本元素,如“FileIHaveFullControl.js”并删除它。

 $("script").each(function(i, j){ if($(this).attr("src").equals("corrupted file url")) $(this).remove(); }); 

关于jquery参考的大部分信息参考http://api.jquery.com/jquery.holdready/

假设您无法访问html文件,因此您无法编辑它(否则问题没有意义),我很害怕我必须通知您脚本src只能设置一次。 改变它是不可能的。

但事实certificate,您可以从dom替换。 我在网上找到了这个function:

 function createjscssfile(filename, filetype){ if (filetype=="js"){ //if filename is a external JavaScript file var fileref=document.createElement('script') fileref.setAttribute("type","text/javascript") fileref.setAttribute("src", filename) } else if (filetype=="css"){ //if filename is an external CSS file var fileref=document.createElement("link") fileref.setAttribute("rel", "stylesheet") fileref.setAttribute("type", "text/css") fileref.setAttribute("href", filename) } return fileref } function replacejscssfile(oldfilename, newfilename, filetype){ var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist using var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for var allsuspects=document.getElementsByTagName(targetelement) for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename)!=-1){ var newelement=createjscssfile(newfilename, filetype) allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i]) } } } replacejscssfile("oldscript.js", "newscript.js", "js") //Replace all occurences of "oldscript.js" with "newscript.js" replacejscssfile("oldstyle.css", "newstyle", "css") //Replace all occurences "oldstyle.css" with "newstyle.css" 

源代码:

http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml