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).
There is a general jquery plugin that loads css and JS files synch and asych on demand. It also keeps track off what is already been loaded :) see: http://code.google.com/p/rloader/
The YUI library might be what you are looking for. It also supports cross domain loading.
If you use jquery, this plugin does the same thing.
In a modern browser you can use
promise
like this. Create a loader function with a promise in it:Then obviously you want something done after the CSS has loaded. You can call the function that needs to run after CSS has loaded like this:
Useful links if you want to understand in-depth how it works:
Official docs on promises
Useful guide to promises
A great intro video on promises
Below a full code using for loading JS and/or CSS
If you use jquery:
Here's the "old school" way of doing it, which hopefully works across all browsers. In theory, you would use
setAttribute
unfortunately IE6 doesn't support it consistently.This example checks if the CSS was already added so it adds it only once.
Put that code into a javascript file, have the end-user simply include the javascript, and make sure the CSS path is absolute so it is loaded from your servers.
VanillaJS
Here is an example that uses plain JavaScript to inject a CSS link into the
head
element based on the filename portion of the URL:Insert the code just before the closing
head
tag and the CSS will be loaded before the page is rendered. Using an external JavaScript (.js
) file will cause a Flash of unstyled content (FOUC) to appear.