Too many characters in character literal - defer CSS - ASP.NET

In this post, I describe how to defer non-critical CSS in ASP.NET without getting the error:

Too many characters in character literal

Screenshot of error Too many characters in character literal


Cause

This error can occur when you copy the suggested code from this defer non-critical CSS page into an ASP.NET page.

<link rel="preload" href="styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">

<noscript><link rel="stylesheet" href="styles.css"></noscript>


Resolution

I used a script tag to load the CSS instead of a link tag:

    <script>
        var link = document.createElement("link");
        link.rel = "stylesheet";
        link.href = "/css/font-awesome.css";
        document.head.appendChild(link);
    </script>

You may also wish to add a noscript tag just in case scripts are disabled:

    <noscript>
        <link rel="stylesheet" href="/css/non-critical.css">
    </noscript>

Please do post in the comments if you have an alternative/better way!


(I used this script to test deferring the loading of a CSS file which included an @import of a Google font.  It caused a FOUT (Flash of Unstyled Text) but, on an almost empty page, reduced the LCP (Longest Contentful Paint) from 1.5 seconds to 0.8 seconds, even though the @import had display=swap.)

Comments

Popular posts from this blog

LG TV This app will now restart to free up more memory

What is the "W" light on a Steelseries keyboard?

Excel Import CSV not using "Use First Row as Headers"