Hi, I trying to use one of two style sheets depending on screen size but it is not working. Here is the code:

<script type="text/javascript">
if(screen.width>= 900){
	document.write('<link href="main.css" rel="stylesheet" type="text/css" />');
}else {document.write('<link href="small.css" rel="stylesheet" type="text/css" />');
}
</script>

It disables the style sheets altogether. Not sure why.
Any suggestions?
Thanks

Dani AI

Generated

's thread shows the classic pitfall: using JavaScript to inject <link> tags via document.write can leave stylesheets missing or the page in a broken state. document.write() is deprecated, behaves differently across browsers, and—if called after the document has loaded—can clear or otherwise disrupt the page. Modern browsers and tools also flag or block its use. (developer.mozilla.org)

Prefer letting CSS decide which rules apply. Two practical patterns work well:

  • Put both rules in CSS and switch with a media query.
  • Or include separate stylesheets and let the browser apply them with the media attribute on the <link> element.

Example (separate files, media on the link):

<link rel="stylesheet" href="main.css" media="screen and (min-width:900px)">
<link rel="stylesheet" href="small.css" media="screen and (max-width:899px)">

Example (single file, in-CSS media queries):

/* base (mobile-first) styles here */

@media (min-width: 900px) {
  /* desktop rules here */
}

These approaches are standard responsive techniques. (developer.mozilla.org)

A couple of practical caveats and alternatives: some browsers may still fetch non-matching linked stylesheets (often at low priority), so if avoiding downloads is critical use one of these options — inline critical CSS, server-side UA detection, or dynamically create and append a link element from script instead of document.write():

var l = document.createElement('link');
l.rel = 'stylesheet';
l.href = (window.innerWidth >= 900) ? 'main.css' : 'small.css';
document.head.appendChild(l);

Test network activity and be aware of the download behavior documented by browser tests. (scottjehl.github.io)

Final checks: include a proper viewport meta for responsive layouts, watch the console for CSP or load errors (which can block injected styles), and follow a mobile-first workflow for simpler overrides and fewer surprises. (web.dev)

Solved

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.