Search code examples
javascriptperformancewebpagetest

How to download a JavaScript file without parsing it?


To improve performance, I want to prefetch a 1.2 MB legacy JavaScript library on my login page. This library is only needed after the user logs in. WebPageTest shows me that Chrome it takes about 700ms of CPU to process the file after it is downloaded. Is it possible to cache the file on the user's browser, but NOT execute/parse the JavaScript?

My ideal flow:

  • load the login page
  • async load the js library using the async and defer attributes of the script tag
    • do not parse, the library isn't actually used until after the user logs in
  • user logs in
  • load the user's home page & load the js library from cache (if present, otherwise fetch from server - not async) and parse
    • I'd like to only pay the 700ms parsing time here

I looked into possibly changing the "type" of the script attribute to text/plain but it seems that this is not possible. Even if this did work it seems to me I would be faced with some sort of eval evil.

Why do I want to do it this way? I have a small window of time where the browser is essentially idle while the user types their credentials. I would like to use that time to download this big library to get a head start loading the next page. I can hydrate the browser's cache by downloading the file in the background, but there is a 700ms spike in CPU that happens after the browser receives the library and parses/executes the file. I would like to avoid this CPU spike on the login page.

You can see the CPU spike on the bottom right of this WPT screen cap: enter image description here


Solution

  • Try using XMLHttpRequest:

    var req = new XMLHttpRequest();
    req.open("GET", "/path/to/your/script.js");
    req.send(); // This line fetches the file
    

    If you want to do something with the contents of this file, set req.onload before the .send() line:

    var req = new XMLHttpRequest();
    req.open("GET", "/path/to/your/script.js");
    req.onload = function()
    {
        console.log(this.response);
    }
    req.send(); // This line fetches the file
    

    Finally, on the server-side, make sure the file is cacheable.