替换脚本标签中的 src 路径

时间:2021-07-21 13:07:16

标签: javascript html reactjs

我正在执行 api 调用,并且在该调用的响应中我正在获取 HTML 数据。 该 HTML 数据有一些脚本和 css 文件要加载,该文件的路径就像 这个

import scipy.io mat=scipy.io.loadmat('u_x.mat')

它正在从我的本地主机获取数据,所以基本上它是点击 localhost/v2/resources.js 来获取脚本文件,现在我想将其更改为其他主机。我该怎么做?

1 个答案:

答案 0 :(得分:1)

你可以这样做(见评论):

// Parse the HTML -- this will _not_ run the scripts
const parser = new DOMParser();
const doc = parser.parseFromString(theHTMLFromTheAPI, "text/html");

// Loop through the `script` elements that have `src`
for (const script of doc.querySelectorAll("script[src]")) {
    // Append a new script element with an updated src
    const newScript = document.createElement("script");
    // Note using `getAttribute`, not the reflected `src` property,
    // to get the source URL so that it isn't calculated relative to the
    // document for us. The URL constructor lets us specify a base URL
    // (https://example.com in this case) that will be used to resolve the
    // relative URL
    newScript.src = new URL(script.getAttribute("src"), "https://example.com");
    // This will run the script from the updated URL:
    document.documentElement.appendChild(newScript);
}

参考文献:

相关问题