Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

216
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda