1 回答
TA贡献1772条经验 获得超5个赞
我认为将文件拆分为多个文件是最好的方法,这样您将从缓存机制中受益。
话虽如此,您可以通过请求文件的一部分然后将响应文本注入script元素并将其附加到文档中来实现您在问题中所要求的内容:
let xhr = new XMLHttpRequest();
xhr.open('GET', 'url/of/the/js/file');
xhr.setRequestHeader('Range', 'bytes=10-40'); // set the range of the request
xhr.onload = function () { // when the request finishes
let scriptEl = document.createElement("script"); // create a <script> element
scriptEl.type = "text/javascript";
scriptEl.textContent = xhr.responseText; // set its content to the response text which is the snippet of code you requested (please take a look at this other SO answer https://stackoverflow.com/a/6433770)
document.body.appendChild(scriptEl); // append that element to the body, the code will then be executed
};
// probably a good idea to handle xhr.onerror as well in case something goes wrong
xhr.send();
添加回答
举报