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 & 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.

Here's the "old school" way to do this, hopefully works in all browsers In principle, you will use the 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); }   

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.

VanillaJS

Here is an example that is based on the CSS link on the file name part of the "code> head element URL:

  & 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;   

before the closing 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

Popular posts from this blog

Verilog Error: output or inout port "Q" must be connected to a structural net expression -

jasper reports - How to center align barcode using jasperreports and barcode4j -

c# - ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value -