通过 URL 参数更改脚本 "src" 并使其正常运行

Change script "src" by URL param and make it functional

我在想是否可以在静态网站上执行此操作,
我有

的 link
https://www.example.com?year=2022&week=05

主要HTML是

<h4 style="color:#FFD700"><strong>TITLE</strong><br></h1>
                        <h3 id="1testing"></h3>
                        <h6 id="2testing"></h6>

// skipped

<script id="results" src="path/to/script/202205.txt"></script>

现在,我想让它根据 URL 参数更新,我有一个 URL 参数(并更新上面的代码)

const queryString = window.location.search;
                console.log(queryString);
                const urlParams = new URLSearchParams(queryString);
                const yrs = urlParams.get('year')
                const wks = urlParams.get('week')
                console.log(yrs);
                console.log(wks);
                document.getElementById('results').src = "path/to/script/" + yrs + "/" + wks + ".txt"

txt文件格式为

document.getElementById("date").innerHTML =// date
"date";
            
// Number 1
document.getElementById("1testing").innerHTML =// 1testing
"1testing";
document.getElementById("2testing").innerHTML =// 2testing
"2testing";

//so on...

然而,我遇到的问题是,src 标签在加载后更新,内容根本没有更新,可能是因为脚本不按顺序,但是我对此了解不多,谁能帮忙解决这个问题?

我认为你应该删除脚本标签和re-add更新的标签。

  let oldScriptTag = document.getElementById('results');

  let newScriptTag = document.createElement('script');
  newScriptTag.id = 'results';
  newScriptTag.src = 'path/to/script/' + yrs + '/' + wks + '.js';
  newScriptTag.textContent = '//script';

  var body = document.getElementsByTagName('body')[0];

  oldScriptTag.remove();

  body.appendChild(newScriptTag);