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

317
Visualizações
How to properly re-emit native events?

I'm working on a script deferrer for WordPress. It takes all of the src attributes for scripts and sets them to null, then, after page interaction, it sets them to their original target. This is all working great, except some scripts rely on events (e.g., load or DOMContentLoaded) to execute, so I need to re-issue those.

There's an answer here that was written in 2018 and updated in April 2021 which says do this:

window.document.dispatchEvent(new Event("DOMContentLoaded", {
  bubbles: true,
  cancelable: true
}));

But it doesn't seem to work (or, at least, the scripts don't respond to it).

My call to the script loader which re-writes the src attributes looks like this:

loadScripts(
    makeGraph(document.querySelectorAll("script[data-type=lazy]")))
    .then(window.dispatchEvent(new Event('DOMContentLoaded',
      {
        bubbles: true,
        cancelable: true
      })))
    .then(window.dispatchEvent(new Event('load')))
    .then(console.log('success'))
    .catch(console.error);

The promise chain always makes it through and logs success.

If I take a piece of JavaScript that's under my control and tell it to alert on those events:

 window.addEventListener( 'load', () => {
    alert('I loaded!');
  })
 alert('I loaded 2');
 window.addEventListener( 'DOMContentLoaded', () => {
    alert('DOM Content loaded!');
 });

I get an alert for "I loaded 2", so it is properly loading the script after I set the src attribute, but the events aren't being caught. Conversely, if I remove my script that's deferring things, and let the scripts load as WordPress would normally have it, the eventListeners fire.

I've also tried attaching the dispatchEvent to both window and window.document and it doesn't seem to make a difference.

This is true at least on Chrome and Safari. So, is there a way to get the "native" events that happen during the course of loading a page to re-fire?

about 4 years ago · Juan Pablo Isaza
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