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?