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

标签 javascript http attributes tags fetch

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

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

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

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

最佳答案

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

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

关于javascript - 如何仅获取 JavaScript 文件的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62417551/

相关文章:

Javascript,更改整个 iframe 页面

java - cURL 发布到 Jenkins 上的 Splunk HEC

php - Guzzle HTTP - 将授权 header 直接添加到请求中

java - 为不同场景配置模拟对象的状态

在网页上仅使用 JavaScript 上传文件

javascript - 需要一个在 yii 中使用 ajax 将值存储在 php 数组中的解决方案

javascript - 我怎样才能改变点击表格的CSS样式

C# - 基本类设计问题

c# - 可能生成编译时错误的自定义属性

javascript - 通过PHP函数获取<select>属性