Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
How to load CSS Asynchronously without Inline Scripts (comply with CSP)

I want to implement Asynchronously loading CSS files for faster performance. However I want security too, so I want my site to have CSP.

<link rel="stylesheet" media="print" class="AOcssLoad" .... onload="this.onload=null;this.media='all';" />

Without going into details it wants me to avoid things like onload and many other JS that are part of elements.

I want it to look like this

<link rel="stylesheet" media="print" class="AOcssLoad" href="" />

Please suggest a way to achieve Asynchronous CSS files without inline JS as used above.

We can use inline <script> tags or seperate JS files.

I tried the below code as an inline JS.. Below is the HTML for the JS,

<script  nonce="" type="text/javascript" data-exclude="true">

var Script = document.getElementsByClassName("AOcssLoad");
for (var i = 0 ; i < Script.length; i++) {
    this.className += " Loading";
    Script[i].addEventListener("load", function({
        this.onload=null;this.media="all";
        this.className += " OnLoad";
    });
}
</script>

While it works, it's highly unreliable.

I cannot comprehend the problem, but I shall say it works only 50% of the times, sometimes just reloading the page can solve/break the problem, with no apparent change to css/html/cache as such.

Please help me improve on this, or build a better approach for it.

Edit:

As Suggested in Comments I tried different methods, including the links to other resources from GitHub.

Those methods are unreliable I would say they work less than 50% of times. However I tried to use jQuery(document).ready() and add media="all" to all the css files, but that increases TBT (Total Blocking Time) thus impacting my site performance

Edit 2:

As many of you are repeatedly pointing out in answers, using DOMcontentLoaded and many other ways can help in doing what I want to implemnt.

However these approaches all contribute to significant increase in TBT (Total Blocking Time).

An approach that doesn't harm the TBT would be appreciated.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I would suggest using fetch().then() and injecting it as a style element:

var stylesheetURLS = ["style.css", "style2.css"]
stylesheetURLS.forEach(url => {
  fetch(url).then(response => response.text()).then(stylesheet => {
    var styleElement = document.createElement("style");
    styleElement.textContent = stylesheet;
    document.head.append(styleElement);
  });
});

I am not sure if fetch is slow, but I wouldn't be surprised if it is.


Alternative to fetch: XMLHttpRequest

var stylesheetURLS = ["style.css", "style2.css"];
stylesheetURLS.forEach(url => {
  var request = new XMLHttpRequest();
  request.open("GET", url);
  request.send();
  request.onload = function() {
    var styleElement = document.createElement("style");
    styleElement.textContent = request.responseText || request.response;
    document.head.append(styleElement);
  }
});

I'm again not sure if this is any faster than fetch

about 4 years ago · Juan Pablo Isaza Denunciar

0

I have tested downloading a css file that takes over 6 seconds to download and I can confirm that downloading does not contribute to the TBT. As stated by google TBT is the time that the browser is unavailable for user input for example when the user clicks a button or scrolls the browser will not react. A long TBT is often caused by the main thread being busy because it has too much work to do. I think processing the CSS (applying all the rules to the html) is what your TBT increases because downloading files is already done in the background (async) and won't be the cause of a long TBT time.

Below an example that the TBT isn't increased when downloading a large file:

TBT: enter image description here

As you can see the downloading takes more than 6 seconds but doesn't add up to the TBT: enter image description here

about 4 years ago · Juan Pablo Isaza Denunciar

0

You could use a vanilla JS function based on jQuery .ready():

document.addEventListener("DOMContentLoaded", () => {
  document.querySelectorAll(".AOcssLoad").forEach(el => {
    el.media = "all"
    console.log(`Loaded: ${el.href}`)
  })
});
<link rel="stylesheet" media="print" class="AOcssLoad" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" />
<link rel="stylesheet" media="print" class="AOcssLoad" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap-utilities.min.css" />
<link rel="stylesheet" media="print" class="AOcssLoad" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap-reboot.min.css" />
<link rel="stylesheet" media="print" class="AOcssLoad" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap-grid.min.css" />
<h1>Hello world!</h1>

However, no matter which solution you choose, be aware you will have to deal with Flash of Unstyled Content (FOUC). Consider other approachs for managing your stylesheet files.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda