html - How to load up CSS files using Javascript? -
Is it possible to import CSS stylesheet in HTML page using Javascript? If so, how can this be done?
The JS JavaScript will be hosted on my site, but I want the user to Here's the "old school" way to do this, hopefully works in all browsers In principle, you will use the This example checks whether CSS has already been added, it only adds once. Put that code in a Javascript file, in the end the user just has to include the javascript, and make sure the CSS path is full, so it is loaded from your server. Here is an example that is based on the CSS link on the file name part of the "code> head element URL: before the closing & lt; Head & gt; tags should be able to import their css files hosted on their website (both CSS file and Javascript file on my server), and their current website should be hosted on my server.
setAttribute unfortunately IE6 does not support it continuously.
var cssId = 'myCss'; // You can encode the CSS path manually to generate the ID. If (! Document.getElementById (cssId) {var head = document.getElementsByTagName ('head') [0]; Var link = document.createElement ('link'); link.id = cssId; Link.rel = 'stylesheet'; Link.type = 'text / css'; Link.href = 'http://website.com/css/stylesheet.css'; link.media = 'all'; Head.appendChild (link); }
VanillaJS
& lt; script type = "text / javascript" & gt; var file = location.pathname.split ("/"). pop (); var link = document.createElement ("link"); Link.href = file .substr (0, file.lastIndexOf (".")) + ".css"; Link.type = "text / css"; Link.rel = "stylesheet"; link.media = "screen, print"; Document. InsertElementsByTagName ("head") [0] .appendChild (link); & lt; / script & gt;
head tag and CSS pages will be loaded before render . External JavaScript (
.js ) will appear in a flash that appears unsaturated material () to access the file.
Comments
Post a Comment