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

166
Vistas
DOMContentLoaded event not working in SPA route change

I have a SPA code where i use the history api and ES6 classes to insert html content into the DOM dynamically.

I have used event listeners such as DOMContentLoaded and checking of location paths before performing scripts but still the content is undefined.

//probably be fetching from a source
document.addEventListener("DOMContentLoaded",() => {
    // function truncateText(text,length) {
    //  if (text.length > length) {
    //      const truncatedText = text.substr(0,length);
    //      return truncatedText + "..."
    //  }
    //  return text;
    // }
    if (window.location.pathname == "/dashboard/posts") {
        const posts = document.querySelectorAll('.post'); //undefined but still exists
        console.log(posts.length == 0 ? false : true)

        posts.forEach((post) => {
            console.log("ran")
            const postTextH = post.children[0].children[1].children[0]
            const postText = post.children[0].children[1].children[1]
            console.log(postText,postTextH + "here")

            postText.innerText = truncateText("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,quis nostrud exercitation ullamco",150)
            postTextH.innerText = truncateText("How to never give up!",70)
        })
    }
})

So my question is how can i run this function after the content in the page is properly loaded and get the posts from the dom.

This is the repo I am using (the structure is same) SPA using history api and ES6 classes

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

0

If you have a SPA application, it means DOMContentLoaded event will be triggered once, when the app is ready (not when you navigate on the routes).

By your logic, this code should be triggered when the location history is changed. You could try to change your DOMContentLoaded event listener to popstate:

window.addEventListener('popstate', function (event) {
    // The URL changed...
});
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