
Originally Posted by
felgall
That will completely overwrite the page.
You should never mix document.write with modern JavaScript.
I don't know about mixing document.write with "modern" JavaScript, but the way the script is structured does not overwrite the page. This is because I pulled the width detection out of the onload section of the script. This means that it finds the width, writes the <link>, loads the page and then overwrites the <title>. Doing it this way allows the page to be validated before changing the <title> content. Validation will fail if the title is dynamically generated as valdiation of the <head> needs a <title>.
I also found a better way of addressing the title which is jQuery rather than JS. For clarification I have appended the whole page code so that youu can run it yourself.
Code:
<!doctype html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="GENERATOR" content="Microsoft FrontPage 5.0" />
<meta name="ProgId" content="FrontPage.Editor.Document" />
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>attaching stylesheet in specific viewport-sizes</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
</script>
<script type="text/javascript">
<!--
var $viewportWidth = $(window).width();
var $whichCSS=($viewportWidth > 596)? "bigViewport.css" : "smallViewport.css";
{ document.write('<link href="'+$whichCSS+'" rel="stylsheet" title="'+$viewportWidth+'" type="text\/css" \/>'); }
$(document).ready(function() {
$(document).attr("title", "viewport width= "+$viewportWidth+"px");
});
//-->
</script>
</head>
<body>
<h1>Heading!</h1>
<p>This is a paragraph!</p>
<p>This is a second paragraph!</p>
<p><br />
This is a paragraph after a line-break</p>
<form action="#">
<p><input type="submit" value="submit" /></p>
</form>
</body>
</html>
Bookmarks