Does anyone know, in the grand scope of things, what are the costs of dynamically adding and removing style sheets from a webpage while it is live (real-time script actions as seen below). I understand that over all CSS compiling speeds are much faster than other compilers, but I would like to understand how fast and if/how that effects HTTP Requests while on the page. I would also like to know how JavaScript affects the page if initially there is a script loaded and then it is swapped out.
I am looking to ease the strain of having to switch from "Full-Screen" to "Mobile" in a browser and cross-platform webpages. I am using a combination of Media Queries through JavaScript and CSS in order to serve all (as many as I can) in different scripts and style sheets.
...
<head>
<meta charset="utf-8">
<title>...</title>
<script type="text/javascript">
function loadSecondary(){
//For full screen do nothing.
if(window.innerWidth > 652 && document.getElementsByTagName("link")[0].id == "mobile") {
//Remove the current style sheet
sheet = document.getElementById("mobile");
sheet.parentNode.removeChild(sheet);
//Load the page again.
loadPrimary();
} else if(window.innerWidth < 651 && document.getElementsByTagName("link")[0].id == "full") {
//Remove the current style sheet
sheet = document.getElementById("full");
sheet.parentNode.removeChild(sheet);
//Load the page again.
loadPrimary();
}
}
function loadPrimary() {
var fileref = document.createElement("link");
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
if(window.innerWidth > 652) {
fileref.setAttribute("id", "full");
fileref.setAttribute("href", 'css/stylesFull.css');
document.getElementsByTagName("head")[0].appendChild(fileref);
console.log("Full");
} else {
fileref.setAttribute("id", "mobile");
fileref.setAttribute("href", 'css/stylesMobile.css');
document.getElementsByTagName("head")[0].appendChild(fileref);
console.log("Mobile");
}
}
</script>
</head>
<body onload="loadPrimary()" onresize="loadSecondary()">
...
Unless the script contains an algorithm with high time or space complexity, the execution should be near instant (less than 10 milliseconds). The css will probably take effect even faster.
The only thing concerning speed or performance to consider is the loading itself of these files. If they are cached, it should also be very fast. However, if they are not cached and have not been accessed previously then their loading time will depend on several factors (such as connectivity, bandwidth, etc.).
These factors of downloading the actual files are all that should be considered with regards to speed and performance. To alleviate it, the files could be preloaded just to trigger the cache. If that is accomplished, there should be no negative hits to performance or speed using or swapping css and javascript files.