Why can I inline JS in a markdown cell, but not HTML?

It appears that one cannot use <script></script> in an Observable HTML cell – is that correct?

For example:

md${case_data[1]['complaint_received']} will produce a result from my data source,

whereas
html<script>${case_data[1]['complaint_received']}</script>
and
html<script>${case_data[1]['complaint_received']}</script>

will not.

I’d like to embed a JS element into a Bootstrap HTML grid, but I’m not sure how one goes about this. Any pointers?

Here’s where I’m at:

1 Like

Ah, apologies! It seems that isn’t needed; this will work:

html`${case_data[1][‘complaint_received’]}`

… but I’d still be interested to learn why <script> is disallowed.

[Digression: to display code in Discourse threads, I recommend either using fenced code blocks (three backticks) or indented code blocks (four spaces). That way you don’t have to escape your backticks like you do with inline code.]

Yes, you should use embedded expressions in your template literals to insert dynamic values into your HTML or Markdown.

If you put a SCRIPT element in an HTML tagged template literal,

html`<script>…</script>`

it gets added to the DOM, but the script doesn’t get executed. That’s standard behavior, per the HTML5 specification, e.g.

When inserted using the document.write() method, script elements execute (typically blocking further script execution or HTML parsing), but when inserted using innerHTML and outerHTML attributes, they do not execute at all.

Only “parser-inserted” scripts (those that exist in the HTML at the time the page was loaded) are executed. Scripts that are created dynamically and added to the DOM are not executed.

4 Likes

Thanks, Mike! This is very clear and helpful.

I especially appreciate that you link in the related references! :slight_smile: