1 回答

TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超5個(gè)贊
我認(rèn)為將文件拆分為多個(gè)文件是最好的方法,這樣您將從緩存機(jī)制中受益。
話雖如此,您可以通過(guò)請(qǐng)求文件的一部分然后將響應(yīng)文本注入script元素并將其附加到文檔中來(lái)實(shí)現(xiàn)您在問(wèn)題中所要求的內(nèi)容:
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();
添加回答
舉報(bào)