Reputation: 1304
I'm modifying some legacy code and I found a web page that loads the JQuery library only to perform the following (this is inside a <script>
tag in the <body>
of the page):
$(document).ready(function(){
//Once the document is ready, run the following code
$("head").append($("<link rel='stylesheet' href='style-"+myCSS+".css' type='text/css' media='screen' />"));
});
I want to convert this code to regular JavaScript and remove JQuery (I'm not against the use of JQuery, I'm against the idea of having to load 90+Kb only to do that).
My idea, but I'm not a JS expert, is to use (in the same position in the page):
headReference.innerHTML = "<link rel='stylesheet' href='style-" + myCSS + ".css' type='text/css' media='screen' />";
Is there any better solution?
Any help is appreciated.
Upvotes: 2
Views: 376
Reputation: 147363
jfriend00's answer is fine, here's another approach which is a bit closer to the jQuery original:
var h = document.createElement('head');
h.innerHTML = "<link rel='stylesheet' href='style-" +
myCSS + ".css' type='text/css' media='screen'>"
document.getElementsByTagName('head')[0].appendChild(h.firstChild);
Upvotes: 1
Reputation: 707198
Here's the equivalent plain javascript:
var head = document.getElementsByTagName("head")[0];
var link = document.createElement("link");
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'screen';
link.href = 'style-'+myCSS+'.css';
head.appendChild(link);
If it matters to load that after the document has loaded (which is probably not required), then you can place this code in a script tag right before the end of the <body>
tag - otherwise, you can put it anywhere in the <body>
element.
Upvotes: 3