0

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?

14
  • 1
    Turned your example into a snippet (so we can run it) it works. I see "hello" twice Commented Dec 1, 2021 at 14:45
  • 1
    @Genarito So show us how you get that script. Commented Dec 1, 2021 at 14:47
  • 2
    And changing const to var? Commented Dec 1, 2021 at 14:55
  • 1
    @JeremyThille, Justinas. I've added a simulated example. Check that the second 'hello' is never printed... Please, don't downvote as the question is not answered in the proposed link... Commented Dec 1, 2021 at 15:47
  • 1
    This is actually a really interesting issue! Can confirm that changing const to var in the json payload makes it work correctly. I assume this is something to do with const being ES6 but I don't really understand why appending it into the DOM would fall back to ES5 Commented Dec 1, 2021 at 15:57

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.