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();
添加回答
舉報