首页 > 解决方案 > 如果脚本已经存在,则从 head 标记中删除脚本

问题描述

所以我在另一个文件夹中调用一个函数,该函数继续下载一个库(jsPDF),然后运行生成的代码。但是,每次我单击触发函数调用的按钮时,脚本都会添加到头部,最终导致程序停止工作。我试图只添加一次脚本,如果添加了它们,请不要添加它们,而是继续使用其余代码。

调用运行函数

var myBtn = document.getElementById('submit1');

//add event listener
myBtn.addEventListener('click', function(event) {

fetch()


});


async function fetch(){

const itemToStore = document.getElementsByClassName("itemName");
const itemQty = document.getElementsByClassName("quoteQty");
const itemPrices = document.getElementsByClassName("quotePrice");
const itemTotal = document.getElementsByClassName("quoteTotal");
const totalCost = "Total Cost" + ":" + document.getElementById("quoteTotalCost").innerText;



fn(itemToStore, itemQty, itemPrices, itemTotal, totalCost)
// getFile()



}

js代码

     async function functionCall(){
        var scripts = document.getElementsByTagName("script");
        for(var i = 0; i < scripts.length; i++){ 
           if(scripts[i].getAttribute('src') == 'https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.28/jspdf.plugin.autotable.js'){
             console.log('found once')
             break;

        }

        else{
          console.log('not found')
          var jQueryScript = document.createElement('script');
          var pdfScript = document.createElement('script');
          var tableScript = document.createElement('script');
          var actualTable = document.createElement('script');
          jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js');
          pdfScript.setAttribute('src','https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js');
          tableScript.setAttribute('src','https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.debug.js');
          actualTable.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/2.0.28/jspdf.plugin.autotable.js');
          document.head.appendChild(jQueryScript);
          document.head.appendChild(pdfScript);
          document.head.appendChild(tableScript);
          document.head.appendChild(actualTable);
          break;
        }
      }

      return true;


       }
      function fn(a,b,c,e,f) {

        functionCall().then(() => {

//rest of the code

错误信息

 ("jQuery.Deferred exception: doc.autoTable is not a function TypeError: doc.autoTable is not a function")

以及一条错误消息说 .then 未定义。

标签: javascript

解决方案


推荐阅读