Search code examples
javascripthtmlhttphtml-head

How to ask browser to cache files for future use


I have an app that is using some large libraries. There are almost 200 js and css files being loaded. And this is how it goes. First it loads 30 of them listed on first html. Than after running some. they trigger loading their own required files. After that library starts, I run a callback that starts other library that loads their own files.

So in first load network activity almost stops several times before it starts downloading 50 other files. And website opening time is almost 20 seconds. But it is mainly because there are big gaps in between library loads.

Since I have the list of all 200 files is there any way that I can ask browser to start downloading all these files and only run in when it is required. So that it will work on downloading all these libraries in the very beginning.

My first approach was I thought maybe I can add file list to HTTP header of first html file. I looked for https://en.wikipedia.org/wiki/List_of_HTTP_header_fields and couldn't see one that I can send list of files that will be used in this html file. And google did not offered me any other solution too at least I couldnt find it.

UPDATE:

This files are all at CDN, I cannot change the headers for assets, I can only change my initial html file headers.


Solution

  • The solution I found is preloading, it allows to load files in advance.

    I had to add tags to my html file:

    <link rel="preload" href="https://example.com/style.css" as="style">
    <link rel="preload" href="https://example.com/example.js" as="script">
    <link rel="preload" href="https://example.com/example.woff2" as="font" type="font/woff2" crossorigin>
    

    More Info at : https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content

    And here: https://www.smashingmagazine.com/2016/02/preload-what-is-it-good-for/

    Preloading Browser support : https://caniuse.com/#feat=link-rel-preload

    Preconnect might also be helpful if you want to start SSL connection beforehand.