What is the correct method for asynchronously loading CSS files in web development?

On a mission to enhance my website's performance, I set out to achieve the perfect score on PageSpeed Insights. Everything was going smoothly until I encountered an issue with CSS delivery.

I initially achieved a flawless result by utilizing the preload tag, but it failed to load in Firefox for some unknown reason. This led me to explore alternative solutions.

I then transitioned to the following approach:

<link rel="stylesheet" href="~/css/site.min.css" media="none" onload="if(media !== 'all')media='all';">
<noscript><link rel="stylesheet" href="~/css/site.min.css"></noscript>

Although this method proved to be effective, PageSpeed Insights did not recognize it, resulting in only an 85 score rating.

A similar outcome occurred when I attempted using

<link rel="stylesheet" href="~/css/site.min.css" media="none"/>
in the head section and
<link rel="stylesheet" href="~/css/site.min.css">
at the end of the body.

Subsequently, I experimented with loading my CSS via JavaScript as follows:

<noscript id="deferred-styles">
    <link rel="stylesheet" href="~/css/site.min.css"/>
</noscript>
<script>
    var loadDeferredStyles = function() {
        var addStylesNode = document.getElementById("deferred-styles");
        var replacement = document.createElement("div");
        replacement.innerHTML = addStylesNode.textContent;
        document.body.appendChild(replacement);
        addStylesNode.parentElement.removeChild(addStylesNode);
    };

    var raf = requestAnimationFrame ||
        mozRequestAnimationFrame ||
        webkitRequestAnimationFrame ||
        msRequestAnimationFrame;
    if (raf) raf(function() { window.setTimeout(loadDeferredStyles, 0); });
    else window.addEventListener('load', loadDeferredStyles);
</script>

Surprisingly, this approach yielded the same unsatisfactory result! Despite employing code from their own site, PageSpeed Insights overlooked it. Can anyone shed light on why this might be the case?

Answer №1

In my experience working with Google PageSpeed, one effective way to enhance CSS delivery is by incorporating inline CSS for the initial section of your webpage. This ensures speedy rendering, while any additional CSS can be placed in an external file. It's also advisable to minimize and merge CSS files utilized on the page. For further information, you can check out this resource optimize css delivery

Answer №2

Just before closing the </body> tag, I implement the following code which functions perfectly.

<script type="text/javascript">

function downloadAtOnload() {
// Adding CSS dynamically
var newCss = document.createElement("link");
 newCss.rel="stylesheet";
 newCss.href= "css/my-css-file.css";
 document.getElementsByTagName("head")[0].appendChild(newCss);

}
if (window.addEventListener) window.addEventListener("load", downloadAtOnload, false);
else if (window.attachEvent) window.attachEvent("onload", downloadAtOnload);
else window.onload = downloadAtOnload;
</script>

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

What is the best way to utilize display:flex and justify-content:space-between, ensuring that the flex-item is centered when there is only a single item present?

How can I center a single flex item in a container with justify-content: space-between in CSS? #container { display: flex; justify-content: space-between; } <div id="container"> <div class='flex-item'></div> . ...

Looking for a way to extract information from two nested objects within an array by utilizing lodash, and then transferring it as a property to a react component

My react components require dynamic preloading of values from nested arrays within an array of data. import React, { useEffect } from "react"; export function loadComponent({ config, LayoutRenderer }) { const loadModules = (name) => q ...

Ensuring that a service is completely initialized before Angular injects it into the system

When Angular starts, my service fetches documents and stores them in a Map<string, Document>. I use the HttpClient to retrieve these documents. Is there a way to postpone the creation of the service until all the documents have been fetched? In ot ...

Applying CSS to align the first line to the left and right, while ensuring that wrapped lines are aligned to the

Struggling with CSS to align drink names and descriptions on a bar's menu. Want the name left aligned and the description right aligned, even if wrapped lines are also right aligned. Current progress can be seen at http://jsfiddle.net/H96XQ/ CSS: . ...

Using inline styles can cause Content Security Policy (CSP) violations in applications

I have been diligently working on an application for quite some time using create-react-app. Recently, I decided to update to the latest version of React only to find out that a new Content Security Policy (CSP) has been implemented. To my dismay, upon tr ...

Sleek transition-ready zoom functionality for THREE JS with clickable controls

Hey there, I've been attempting to animate a transition between scenes in THREE js for quite some time now. I have successfully cleared the scene and recreated the next one, but the transition between them is proving to be quite challenging. I have cr ...

Expanding the axes using Google Charts

Seeking to Expand Y-Axis I am attempting to stretch the Y-axis so that it counts up to 300 instead of just 100. The issue arises when I adjust the Y-axis to reach 300, as the values remain in the same position as they did when counting to 100. Fo ...

Angular Tip: Display data in a dropdown using a select element

When I have two select elements and want to display values if they exist: page.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app ...

Css beforehand, unique subject matter

Trying to use a jQuery plugin that has CSS code like this: .icon-eye:before { content: '\56'; } On the plugin's site, it displays as an eye icon. However, when I install the plugin on my local PC, I see 'V' instead of the ey ...

Issue: the module '@raruto/leaflet-elevation' does not include the expected export 'control' as imported under the alias 'L' . This results in an error message indicating the absence of exports within the module

Looking for guidance on adding a custom Leaflet package to my Angular application called "leaflet-elevation". The package can be found at: https://github.com/Raruto/leaflet-elevation I have attempted to integrate it by running the command: npm i @raruto/ ...

What is the best way to invoke a custom hook that returns a value within the useEffect hook?

I have a unique situation where I am using a custom hook that returns an object based on the parameter it receives. I now need to modify this behavior by recreating the object with updated parameters within the useEffect function. The challenge is that I c ...

Unable to set background-image on Node (Limited to displaying only images sourced from Flickr)

I am experiencing difficulty with the background-image node property not functioning properly. In order to test this issue, I am using the "Images & breadthfirst layout" demo as an example (accessible at https://gist.github.com/maxkfranz/aedff159b0df0 ...

WebVR - lack of orientation and position data from PositionSensorVRDevice

I'm attempting to enable Oculus Rift DK2 orientation input for WebVR, using either Three.js' VRControls (examples/js/controls/VRControls.js) or directly from the PositionSensorVRDevice. However, the values of orientation and position in the Posi ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

The React Bit Dev module is showing a 404 error

Attempting to incorporate the semantic-ui-react table reusable component from the Bit.dev community into my application. The link I am using is: To add this component to your application, use: npm i @bit/semantic-org.semantic-ui-react.table However, when ...

What is the best method to assign values to AngularJS controller variables using Python Selenium or the JavaScript console?

After utilizing Python Selenium and AngularJS for a few months, I am currently attempting to adjust certain AngJS variables (specifically the aslider filter from here) and refresh the page in order to extract some data. Below is the code I am using for thi ...

What are the benefits of incorporating various custom fonts through @font-face?

I feel like I must be overlooking something very simple. I have been using a single custom font with a normal font face: @font-face { font-family: CustomFont; src: url('CustomFont.ttf'); } Everything works perfectly when I use this font ...

Transmitting information following successful password verification

Currently, I am working on a form to insert users into a database. Along with this, I have two scripts in place - one for password validation and the other for AJAX retrieval of PHP results. As of now, these two scripts are functioning independently. How ...

"Include the 'unsafe' prefix at the start of the URL in AngularJS

Whenever I attempt to access app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 within my app, the URL gets parsed as ==> unsafe:app://csttree?featuretype=cst_issue&verticalid=2132321&l1=3213&l2=3242 Is ...

Determine the output based on the data received from the ajax post request

I am seeking a way to validate my form based on the data returned. Currently, the validation only returns false if the entire post function is false. Is there a solution to differentiate how it is returned depending on which condition is met? This is my ...