Force CSS to load if it does not

tekagami 0 Tallied Votes 256 Views Share

Sometimes a css file wont load because of a slow connection or a conflict between scripts (or just any other reason). This specially problematic on mobile websites (looking at you IOS) where many standards are applied. So this little script will add a link tag to the head tag and load a css file.

This example takes into consideration responsive design. You should modify it to accomodate your design (and file names).

What this script does is take the computed style of a div (poller) and checks if conforms to what is expected from the CSS rules and if not adds a link tag to the head which is selected by checking the page width.

<script>
function forcecss(){
var el = document.getElementById('poller');
var comp = el.currentStyle || getComputedStyle(el, null);

var  polldisplay = comp.display;
if ((polldisplay != 'block')||(polldisplay != 'none')){
var ancho = document.body.scrollWidth;
if (ancho < 959){
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", "css/mobile.css")
document.getElementsByTagName("head")[0].appendChild(fileref)
} else {
var fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("href", "css/styles.css")
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
}
window.onload = forcecss;
</script>



<div id="poller">I am displayed as block in mobile BUT not in desktop because </div>
tekagami 23 Newbie Poster

tested in Chrome 31.0.16 (windows), IE11 and Firefox 26.

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.