如何仅获取 JavaScript 文件的一部分?

How to source only part of a JavaScript file?

我有一个非常大的 JavaScript 文件(超过 10mb),按字节偏移

分成不同的部分

我想将此 JavaScript 文件作为不同的片段加载到我的 HTML 代码中,具体取决于字节偏移量,使用脚本标记,这样只有 JS 文件的那部分已加载

我知道我可以在我的服务器上设置它以接收 GET 请求查询字符串,例如 ?bytes=10-40src url 的末尾,但我当时想知道是否可以仅使用客户端代码来执行此操作,而不向服务器添加任何内容(假设服务器无论如何都支持 accept-ranges:bytes,或者最好仅供离线使用,如果可能的话,只包含离线 js文件并以这种方式获取内容)

这是否可以在客户端 JavaScript 中完成(没有其他 XMLHttpRequestfetch)?

我认为将文件拆分为多个文件是最好的方法,这样您将受益于缓存机制。

话虽如此,您可以通过请求部分文件然后将响应文本注入 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 

    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();