Utilize browser caching effectively with Firebase and Angular 5 to optimize website performance

After running my Angular 5 website through Google's PageSpeed Insights, it flagged an issue regarding leveraging browser caching. The specific files mentioned were:

https://use.typekit.net/####.css (10 minutes)
https://www.googletagmanager.com/gtm.js?id=GTM-#### (15 minutes)
https://####.firebaseapp.com/assets/svgs/###.svg (60 
minutes)

My firebase.json file is structured as follows:

    {
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "headers": [
      {
        "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)",
        "headers": [
          {
            "key": "Access-Control-Allow-Origin",
            "value": "*"
          }
        ]
      },
      {
        "source": "**/*.@(js|css)",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "max-age=604800"
          }
        ]
      },
      {
        "source": "**/*.@(jpg|jpeg|gif|png|svg)",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "max-age=604800"
          }
        ]
      },
      {
        "source": "404.html",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "max-age=300"
          }
        ]
      }
    ]
  },
  "functions": {
    "predeploy": [
      "npm --prefix $RESOURCE_DIR run lint"
    ],
    "source": "functions"
  }
}

I tried implementing solutions from a post on utilizing browser caching in Firebase hosting (How to Leverage Browser Caching in Firebase hosting), but unfortunately, the error persists even after rerunning PageSpeed Insights. Any advice or guidance on resolving this issue would be greatly appreciated since I am relatively new to Angular. Thank you for your help!

Answer №1

There are 2 possible solutions

1. Host the external files on your own domain.

Download the following 3 files and host them from your application server. By doing this, you can manage the caching settings effectively. Ensure you keep a current version of any third-party CSS and JS files to stay up-to-date with updates.

https://use.typekit.net/####.css (cache for 10 minutes) .  
https://www.googletagmanager.com/gtm.js?id=GTM-#### (cache for 15 minutes) .   
https://####.firebaseapp.com/assets/svgs/###.svg (cache for 60 minutes)

2. Workaround for Google PageSpeed Insights

It's important to note that Google PageSpeed Insights is just a guideline and not an absolute rule. You may get better insights using other tools like . However, you can implement the following workaround to dynamically load the affected CSS and JS resources only if the user agent is not Google PageSpeed Insights. This way, the problematic resources won't load during the speed test, potentially improving your score.

<script>
if (navigator.userAgent.indexOf("PageSpeed Insights")==-1) {
...
...
</script>

Answer №2

Don't pay too much attention to the 3 suggestions given by Google PageSpeed (and similar tools).

Interestingly, some files served from a Google CDN (like fonts) trigger errors on Google PageSpeed and other similar tools (such as Lighthouse).

I believe Google should address this issue in their tools.

Google PageSpeed is not about winning a race or achieving a perfect score of 100... it simply provides a basic overview of performance. Sometimes it may flag an issue that doesn't actually exist, or miss one that does.

The real problem arises when SEO "experts" use these results to judge your website (a situation many developers can relate to...).

Please take action, Google!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with Angular.js: JSON response not working in $http request

After extensive searching, I'm still unable to find a solution for my first Angular.js app issue: The problem lies with a search form that sends a request to a web server to retrieve a JSON object. Unfortunately, the request fails and triggers the er ...

Delete every instance of a specific key in a JSON file

I'm trying to figure out how to delete all instances of a specific key in a JSON file. For example, I need to remove all occurrences of the "rating" key in the JSON below: Here is the current JSON: { "player": { "rating": "99", "rarity": " ...

Dynamically Updating Radio Button Status in Angular 7 Using Material Design

I am currently working on an Angular Material application that includes radio buttons. My goal is to update the selected button based on data retrieved from a database. While everything seems to be functioning properly, I have noticed that the checked butt ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

Error in TypeScript: Unable to assign type 'string' to type 'number | ""'

I am new to TypeScript and struggling to comprehend the error message below. Type '{ order: string; }[]' is not compatible with type 'TestType[]'. Type '{ order: string; }' is not assignable to type 'TestType'. ...

What is the best way to remove all selected items in a dropdown menu?

My issue pertains to Angular and Typescript. I am facing a challenging problem with a dropdown menu that has 3 items. The unique aspect is that I am not utilizing the standard select HTML tag; instead, I am using my company's custom toolkit, which ser ...

Implement the retrofit function to fetch and update with fresh data

Recently, I have been facing an issue with my Retrofit implementation where it used to work perfectly a few weeks ago. Now, whenever I run the code, it only loads the data once. Even if I make changes to the text or add new values in the JSON data, it stil ...

Ways to rearrange an object with javascript

I am looking to restructure my object by removing a nesting. How can I achieve this using JavaScript? Actual: var a = [ { clickedEvents: { 'event-element': 'a', 'event-description': & ...

Tips for successfully transferring values or parameters within the Bootstrap modal

How can I create a cancel button that triggers a modal asking "Are you sure you want to cancel the task?" and calls a function to make an API call when the user clicks "Ok"? The challenge is each user has a unique ID that needs to be passed to the API for ...

Issues with animations in Ionic 3 and Angular 4 not functioning as expected

Working on a component to animate an accordion list, I made all the necessary changes such as importing import { BrowserModule } from "@angular/platform-browser"; and import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; as well ...

Leveraging prisma and typescript models simultaneously

In my TypeScript models, I frequently utilize const assertions: const ListingVehicleTypes = [ "car", "motorcycle", "caravan", "camper_trailer" ] as const; interface LISTING { vehicleType: typeof ListingVeh ...

Angular: Refresh Mat-Table data following any changes

I'm currently working with a Mat-table that has expandable rows, each containing an update functionality for the data. While the POST and GET requests are functioning properly, I encounter an issue where I need to reload the page in order to see the u ...

Retrieve JSON data using AJAX one by one

I am facing a minor issue with my code. Let's consider a JSON structure like the one below: [{"img":"john.png","name":"John","username":"@john"}, {"img":"mark.png","name":"Mark","username":"@mark"}] My desired data organization is: John @john john. ...

Achieving automatic checkbox selection in Angular 6 through passing a value from one component to another

My page named second.html contains the following code: <div class="col-lg-4 col-md-4 col-sm-4"> <input type="checkbox" class="checkmark" name="nond" [checked]="r=='true'" (change)="nond($event, check)"> ...

Having trouble implementing basic CSS on an Angular Materials component

Check out this Stackblitz example. I am attempting to add the CSS style color: blue to the element with class mat-button-toggle-label-content, however, it does not seem to be working. Interestingly, a similar CSS style is successfully being applied to a ...

What is the solution for fixing an error that says "There is no 'style' property on the 'Element' type"?

I'm struggling to fix an error in my JavaScript code. I created a script to display a tab indicator when a tab is clicked, but I keep getting the error message: "Property 'style' doesn't exist on type 'Element'". The tabs them ...

What exactly is the meaning of "Dispatch<SetStateAction<boolean>>" in React with TypeScript?

I am currently working on writing Frontend Tests for React Components in TypeScript. The code I am using belongs to a more seasoned programmer, so some of the data types are unfamiliar to me. One particular prop has been defined with the data type "Dispa ...

What is the Typescript compiler utilized by Visual Studio 2015 when compiling on save?

Currently using Visual Studio 2015 Update 3 with TypeScript 2 for VS installed. I have a basic ASP.NET Core MVC web application with a few simple TypeScript files. The project contains a tsconfig.json file in the root folder with "compileOnSave": true. I ...

Making a call to Ajax while specifying the contentType as 'application/json'

After some troubleshooting, I discovered that removing the content-Type works fine. However, the jsonitem received on the PHP side is showing syntax errors. From my research, it seems like specifying the content type when sending Json objects is crucial. ...

Passing props to child selector within ngrx selector in Angular 7: A step-by-step guide

Is it possible to pass props to all child selectors in the store/index.ts file of ngrx 7 for Angular 7 like this: In the component, I will make the following call: this.filteredUser = this.store.pipe(select(selectVisibleBooks, {id: this.id})); expo ...