0

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.

Edited by tekagami: code format

<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>
1
Contributor
1
Reply
16
Views
3 Years
Discussion Span
Last Post by tekagami
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.