Prevent reloading images on route change - Angular 6

I have a component in my Angular app. It has a div, which has a background image set to a variable in the component class like this:

<div class="home-background" [style.background-image]="'url('+ bgImage +')'">.......</div>

Whenever I navigate to this component, in the network tab in chrome, I can see that it refetches the background image every time. The image size is 500Kb and it shows a blank area for half a second.

Is there a way to force the div to use the cached image instead of fetching it from server on every navigation to this component?

2 answers

  • answered 2019-08-13 06:56 Ashish Sharma

    You can cache the image for the first time when it loads using service worker. Service worker allows you to keep the content ready which is frequently required to improve user experience.

    self.addEventListener('fetch', function(event) {
    console.log(event.request.url);
    console.log(event.request.url);
    
    event.respondWith(
    caches.match(event.request).then(function(response) {
    return response || fetch(event.request);
    })
    );
    })
    

    this code is for a sample js-html project where I have cached all fetch data and when requested, first I have checked the data in cache, if not found then gone for http.

    Angular has a seprate package for adding service workers which can do all these task under the hood you. You can refer to below link Angular PWA Documentation

  • answered 2019-08-13 08:27 Francesco

    I wrote an article explaining - step by step - how to inject PWA features into an Angular project.
    You can read more here.

    As it has already being suggested, you can use service workers to cache assets.

    If you run the following command in the CLI ( Angular add schematics):

    ng add @angular/pwa
    

    It will setup almost everything for you (you can find all the details in my article at the link above).

    By default the command above will cache all files in the asset folder with a lazy strategy (that means they will be cached after they have been requested at least once).

    Below the generated file:

    {
      "$schema": "./node_modules/@angular/service-worker/config/schema.json",
      "index": "/index.html",
      "assetGroups": [
        {
          "name": "app",
          "installMode": "prefetch",   <- Those files are cached immediately by the SW
          "resources": {
            "files": [
              "/favicon.ico",
              "/index.html",
              "/*.css",
              "/*.js"
            ]
          }
        }, {
          "name": "assets",
          "installMode": "lazy",     <- Those files are cached after a first request
          "updateMode": "prefetch",
          "resources": {
            "files": [
              "/assets/**",
              "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
            ]
          }
        }
      ]
    }
    

    If you want to provide those images eagerly and make them available even if the user is offline, you can set installMode: prefetch in the config file that the previous command creates for you (ngsw-config.json).

    With this you would be able to deliver the images from the cache and you can also set a lifetime. In the article I also describe how to cache API GET Requests, if you want to further improve your app.