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

159
Vistas
Functions accessible from different scripts but constants aren't when added via JQuery html()

I'm working on a legacy system where an endpoint sends an HTML content that when received in the frontend is added to a div: $('#some-div').html(htmlContent).

That works fine, but I am observing something strange, when I define some constants in a <script> they appear as undefined in the scripts that continue:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
  // This simulates the content retrieved from the server
  let contentFromBackend = JSON.parse("{\"text\":\"<script>\\n    const someConst = \'hello\'\\n\\n    function someConstFn() {\\n        return \'hello\'\\n    }\\n<\/script>\\n\\n<script>\\n    console.log(someConstFn()) \/\/ This works!\\n    console.log(someConst) \/\/ This fails saying that someConst is undefined!\\n<\/script>\"}")['text']

  // Appends to div
  $('#some-div').html(contentFromBackend)
})
</script>

<div id="some-div"><div>

If the content is generated statically (for example, with a Template Renderer like Twig or plain HTML) both the constant and the functions work perfectly. var also works fine. Why does this happen?

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