Search code examples
htmlnoscriptlynx

Is using partial HTML comment in noscript to hide content when javascript is disable, guarantee to work everywhere?


I want my website to work on text-based browsers like lynx

There's some part of the HTML that are useless in it like the profile photo

I tried the most upvoted solution put here Is there a HTML opposite to <noscript>?

which is

<head>
    <noscript><style> .jsonly { display: none } </style></noscript>
</head>

However Lynx does not hide it

What I found to work is doing this

<body>
    <noscript> <!--  </noscript>
         <img src="foobar.png">
    <noscript> -->  </noscript>
</body>

This works and it seems to work on all browsers I have tested, i.e the image is hidden when javascript is disabled, and shown otherwise.

However I would like to know if it is a documented behaviour in HTML5 parser or if it's just an edge case that everybody has implemented the same way ?


Solution

  • It's guaranteed to work in every User Agent that does respect the HTML parsing rules, yes.

    If you're ready to dive into this wonderful machinery...

    Assuming the scripting flag is enabled, and we already processed the <body> tag.

    If the scripting flag was disabled though,

    • When the first <noscript> tag is met, we just insert an ordinary element out of it.
    • We are still in the "in body" insertion mode and the tokenizer is still in the data state.
    • The < character leads the tokenizer to the tag open state.
    • The ! one, to the markup declaration state.
    • And the next two --, to the comment state.
    • From there everything until the next --> sequence will be part of the comment token that will get emitted to the parser and thus treated as text.
    • The parser inserts the comment
    • It then gets the closing </noscript> token and inserts the current node, with the comment inside.