Markdown, CSS, JavaScript: Rendered MD differs from MD converted to HTML

This is a weird one. The overall picture:

  • A JavaScript script is defined for MD documents. The code syntactically and semantically correct.
  • The script is triggered by the DOMContentLoaded event and reads the query parameters of all img elements.
  • It uses the keys and values passed in the query parameter to set the img elements’ style attribute.

The MD document looks like this:

This is the first line of text, followed by a stand-alone image

![](IMG_4252.jpg?width=50%&border=1px solid red)

and another line of text

and the JavaScript is

document.addEventListener('DOMContentLoaded', e => {
  const images = document.querySelectorAll('img[src*="?"]');
  images.forEach(img => {
    // get the query string
    const searchParams = URL.parse(img.src).searchParams;
    const styling = [];
    for (const [key, value] of searchParams) {
      styling.push(`${key}:${value}`)
    }
    img.style=styling.join(';') + ';';
  })
})

With this setup, the MD file is rendered as if the JS code were never executed.

On the other hand, converting the MD to HTML results in an HTML document that behaves perfectly correct: On displaying the rendered view, the image is only half as wide and has a thin red border.

I do remember that people used event listeners for DOMContentLoaded that worked fine at MD rendering time, eg here and here

FYI: The effect is independent of the renderer, i.e. MMD6 and the new DT renderer both seem to not run the code in the event listener.

Finally, two screenshots of the side-by-side view, first MD, than HTML


And here’s what the developers tools in FF show me. Take note of the style attribute that is correctly added by the JS code.

<html dir="auto" lang="de"><head>
<title>JS styling on the fly</title>
<meta name="generator" content="DEVONthink 4.3">
<style><!--
CODE OMITTED since it doesn't matter here
--></style>
<script type="text/javascript" src="file:///Users/ck/Develop/test/style-on-the-fly.js"></script>
<meta charset="utf-8">
</head>
<body>
<p>This is the first line of text, followed by a stand-alone image</p>
<figure>
<img src="IMG_4252.jpg?width=50%&amp;border=1px%20solid%20red" alt="" style="width: 50%; border: 1px solid red;">
<figcaption></figcaption>
</figure>
<p>and another line of text</p>
</body></html>

This URL is not a properly formatted, did you try it with simple and proper URLs too?

Do you mean because of the spaces? Using %20 instead doesn’t change a thing, and as can be seen in the screenshot, the URL gets correctly rendered with %20 in the converted HTML.

Or do you mean something else?

I was just wondering whether the poor formatting confused the parser. Obviously not, especially as it’s an issue for MultiMarkdown too.