Is it possible to import css stylesheets into a html page using Javascript? If so, how can it be done?
P.S the javascript will be hosted on my site, but I want users to be able to put in the <head>
tag of their website, and it should be able to import a css file hosted on my server into the current web page. (both the css file and the javascript file will be hosted on my server).
I guess something like this script would do:
This JS file contains the following statement:
The address of the javascript and css would need to be absolute if they are to refer to your site.
Many CSS import techniques are discussed in this "Say no to CSS hacks with branching techniques" article.
But the "Using JavaScript to dynamically add Portlet CSS stylesheets" article mentions also the CreateStyleSheet possibility (proprietary method for IE):
Call the following function to dynamically load CSS or JavaScript file.
Pass the complete file path with the name as
filename
argument.If you want to know (or wait) until the style itself has loaded this works:
You may use for this YUI library or use this article to implement
Here's a way with jQuery's element creation method (my preference) and with callback
onLoad
:I know this is a pretty old thread but here comes my 5 cents.
There is another way to do this depending on what your needs are.
I have a case where i want a css file to be active only a while. Like css switching. Activate the css and then after another event deativate it.
Instead of loading the css dynamically and then removing it you can add a Class/an id in front of all elements in the new css and then just switch that class/id of the base node of your css (like body tag).
You would with this solution have more css files initially loaded but you have a more dynamic way of switching css layouts.