Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason to add a simple static <style> tag via document.write()?

I just looked at the page source of a random app page on apptivate.ms and noticed this JavaScript in the <head>:

<script type="text/javascript">
        document.write("<style type=\"text/css\">.app-description { max-height: 600px }</style>");
</script>

It is obviously totally static on the client side so I wonder what the use-case there is. Since they Stack Exchange developers (who are behind apptivate.ms) are pretty smart I'm sure there is some reason for it, but I can't figure out which. I guess it's related to delaying the rule from becoming active until the whole document is loaded but I'd expect the rule to be applied as soon as the browser "sees" the new tag...

like image 359
ThiefMaster Avatar asked Nov 30 '12 14:11

ThiefMaster


People also ask

What does document write () function do?

The document. write() method writes a string of text to a document stream opened by document.

Why we use document write in JavaScript?

The write() method in HTML is used to write some content or JavaScript code in a Document. This method is mostly used for testing purpose. It is used to delete all the content from the HTML document and inserts the new content. It is also used to give the additional text to an output which is open by the document.

Why is document write () not recommended anymore?

. write is considered a browser violation as it halts the parser from rendering the page. The parser receives the message that the document is being modified; hence, it gets blocked until JS has completed its process.


1 Answers

It's because part of the content of the .app-description element is hidden, and can be shown by clicking a "Show more" button.

If JavaScript is disabled, the button won't work, so if the style in question was directly in the stylesheet, you could never see the rest of the content. By adding that style in the <head>, with JavaScript, it ensures that users with JS enabled will not see all the content at once, but will instead get the "enhanced" experience, and those without JS enabled will still be able to use the site.

Here's a screenshot when JS is enabled. The "show more" button uses JavaScript to expand the element to full height:

enter image description here

This is a nice approach to progressive enhancement - by using document.write to insert the new style element inside the head you avoid any possible flash of unstyled content (in this case, the developers could have waited until DOM ready and then used JavaScript to add the maxHeight property dynamically, but that would have resulted in users seeing the full height briefly before the JavaScript executed on DOM ready).

like image 62
James Allardice Avatar answered Sep 28 '22 05:09

James Allardice