Thalatta Thalatta - 3 months ago 10
CSS Question

document.write() for adding a stylesheet causes document to be blank

I am trying to add a stylesheet only on the condition that the browser is either Chrome or Opera. I have the following control flow using the YUI library:

if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
document.write("<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>");
}


Here is the conditionally attached css file,
style_ticket_printing_header.css


@page
{
size: auto;
margin: 0mm;
}


Here is the full HTML:

https://gist.github.com/ebbnormal/b1cff9d45914bc2f63a4

When I run the page in Chrome, none of the
<div>
s that are defined within the
<body>
tag are rendered or are displayed within the DOM.

What is particularly confusing is that, when this CSS is loaded in the normal way (by simply referencing it via a
<link>
tag in the
<head>
of the page, all of the DOM are loaded perfectly.

And finally I know that it successfully renders the condition of seeing it is chrome as I formerly had an alert message in the body of the if block which successfully executed.

Answer

document.write() for adding a stylesheet causes document to be blank

Right. When you use document.write after the main page parsing is complete, it implicitly does a document.open, which wipes out the page.

Instead, use createElement and appendChild:

if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
    var link = document.createElement('link');
    link.rel = "stylesheet";
    link.media = "print";
    link.type = "text/css";
    link.href = "../../../css/style_ticket_printing_header.css";
    document.querySelector("head").appendChild(link);
}

Or if you really like to use HTML: :-)

if ((Y.UA.chrome > 0) || (Y.UA.opera > 0)){
    document.querySelector("head").insertAdjacentHTML(
        "beforeend",
        "<link rel='stylesheet' media='print' type='text/css' href='../../../css/style_ticket_printing_header.css'/>"
    );
}

(Both of the above assume you have a head element, which you presumably do; it's required in a well-formed HTML document, either explicitly or because the browser adds it for you [but explicit is best].)


About querySelector: It finds the first element that matches a CSS selector. It's supported by all modern browsers, and also IE8. (There's also querySelectorAll, which finds a list of matching elements.)