【问题标题】:How to source only part of a JavaScript file?如何仅获取 JavaScript 文件的一部分?
【发布时间】:2020-06-17 05:44:06
【问题描述】:

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

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

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

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

【问题讨论】:

  • hmm 非常有趣的提议,我以前从未听说过这是可能的,但我想什么都可以
  • @bluejayke 是的,这就是所希望的,知道这是否可能在这里吗?
  • 看起来很奇怪,你怎么确定你有你真正需要的代码?
  • @epascarello 你是什么意思?我有另一个索引文件,它跟踪文件中不同函数/数据的字节偏移量

标签: javascript http attributes tags fetch


【解决方案1】:

我认为将文件拆分为多个文件是解决此问题的最佳方法,这样您将受益于缓存机制。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    相关资源
    最近更新 更多