How to source only part of a JavaScript file?

Viewed 170

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)?

1 Answers

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