Loading css in javascript depending on URL Protocol

Hello fellow JavaScripters, here is some code that I am working on to load styles into a page depending on the protocol of the URL. It seems to load the .css files correctly in FF but in IE I get an “document.head is null or not an object” error. was wondering if I cold get any assistance.

Here is the code:

window.onload = function(){
var protocol = document.location.protocol;
var ref = document.createElement(‘link’);
ref.setAttribute(‘rel’,‘stylesheet’);
ref.setAttribute(‘type’,‘text/css’);
if(protocol == ‘http:’){
ref.setAttribute(‘href’,‘IE.css’);
}else if(protocol == ‘https:’){
ref.setAttribute(‘href’,‘IEhttps.css’);
}
document.head.appendChild(ref);

You are opening a window.onload function but not closing it; you need a brace and a semicolon on that last line. :slight_smile: FireFox and other modern browsers are more forgiving then IE and will sometimes overlook simple errors like this.

Optimized code:

window.onload = function() {
    var protocol = document.location.protocol;
    var ref = document.createElement('link');
    ref.setAttribute('rel', 'stylesheet');
    ref.setAttribute('type', 'text/css');
    if (protocol == 'http:') {
        ref.setAttribute('href', 'IE.css');
    } else if (protocol == 'https:') {
        ref.setAttribute('href', 'IEhttps.css');
    }
    document.head.appendChild(ref);
};

Going by my code the last brace and semi colon are underneath the document.head.

Im sorry, Originally had it in my code, I did not copy it into the forum. But, the Brace and semicolon are there originally.

This is just a stab in the dark and is completely untested. But you could try substituting this line of code:

document.head.appendChild(ref);

For this:

document.getElementsByTagName("head")[0].appendChild(ref);

Ya just tried that, same issue. So frustrating

Got past the main issue, now I’m getting a object expected “line 195 char 1”

What is the code that is on line 195?

Sorry forgot to mention that this worked to get pass initial issue. code onl ine 195 is
document.getElementsByTagName(“head”)[0].appendChild(ref);

It works for me in IE. You might have a caching issue if you uploaded the page, that you can resolve with Ctrl-F5 or Shift-F5

Otherwise, can you link us to a test page that demonstrates the problem?

Just wanted to thank everyone for there help, I am able to get it to work by. The problem is it now takes almost a minute to apply the style to the page. here is the finishing code.

function applyStyleSheetByProtocol(http, https) {
var protocol = document.location.protocol;
var ref = document.createElement(‘link’);
ref.rel = “stylesheet”;
ref.type = “text/css”;
if(protocol == ‘http:’){
ref.href = http;
}else if(protocol == ‘https:’){
ref.href = https;
}
document.getElementsByTagName(‘head’)[0].appendChild(ref);
};