Is it a bad idea to link CSS files inside the body
?
I've read that the browser is forced to start CSS rendering over again if it finds another CSS file outside of head
, just because it might need to apply styles to elements it's already rendered. Also I don't think the HTML will validate properly (I need to confirm this).
Are there any other reasons?
The questions have been answered (is it bad, why...) but the correct way to achive that if you can't add your links (or scripts) in the header, is to dynamically insert them with javascript. It's also sometime a good idea for improving the speed of your code. For the links you can use this function:
function loadCss(url) {
var link = document.createElement("link");
link.type = "text/css";
link.rel = "stylesheet";
link.href = url;
document.getElementsByTagName("head")[0].appendChild(link);
}
You should use a JavaScript file loader like require.js for the scripts.
The only reason I've seen people use to justify doing this is when they're using certain templating engines, and they can't arbitrarily change the stylesheets linked in the head when loading new content or a particular view (in the case of MVC frameworks).
Either way, this should be avoided at all costs as it's sloppy, and improper. Instead, always develop your projects in such a way that you can get an arbitrary stylesheet into the head at any time. I generally do this by cycling through a stylesheet array in the head. That way, if I need to add a new stylesheet, I simply add its pathname to the array to be printed in the head.
<?php
$styles = array();
$styles[] = "css/main.css";
$styles[] = "css/text.css";
?>
<head>
<?php foreach ($styles as $style) { ?>
<link href="<?php print $style; ?>" rel="stylesheet" type="text/css" />
<?php } ?>
</head>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With