2

I have a really large JavaScript file (like over 10mb), that is split up into different sections, by byte-offset

I want to load this JavaScript file into my HTML code as different snippets, depending on the byte offset, using a script tag, such that only that part of the JS file would be loaded

I'm aware I could set it up on my server to take in a GET request query string like ?bytes=10-40 at the end o the src url, but I was wondering if its possible to do this with just client-side code, with no additions to the server (assuming the server anyways supports accept-ranges:bytes, or preferably just for offline use, if thats even possible, to just include the offline js file and get the contents that way)

Is this possible to do in client-side JavaScript (with no other XMLHttpRequest or fetch)?

2
  • Seems rather weird, How would you be sure you have the code that you actually need? Commented Jun 16, 2020 at 21:50
  • @epascarello what do you mean? I have another index file that keeps track of the byte offset of the different functions /data in the file Commented Jun 17, 2020 at 0:04

1 Answer 1

1

I think splitting the file into multiple files is the best approach to this, that way you'll benefit from the caching mechanism.

With that said, you can achieve what you asked for in the question by requesting part of the file and then injecting the response text into a script element and appending that to the document:

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.