How to Load Up CSS Files Using JavaScript

How to load up CSS files using Javascript?

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.

var cssId = 'myCss';  // you could encode the css path itself to generate 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.example/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}

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:

<script type="text/javascript">
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.getElementsByTagName( "head" )[0].appendChild( link );
</script>

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.

load css file using javascript

Why are you trying to do this? What benefit are you expecting?

I've never come across a situation where this is a good idea. CSS files are usually pretty small, so you aren't really gaining much by loading them dynamically. Just do the load in the head tag.

Anyway, the code you have should work. Just be sure that path is correct (it will be relative to the html file you're running)


Another solution would be to load an html file with all of the markup you need, and append it to the body. Check out the jQuery.load function The line below will load gameMarkup.html into the body tag.

$( "body" ).load( "gameMarkup.html" );

You can include all of the markup for your game here (not just styles). Generating elements with js can be useful, but it makes the code harder to maintain.

If you aren't using jquery, you can do the same thing with XHR, but it will be a lot more lines of code.

Dynamically loading css file using javascript with callback without jQuery

Unfortunately there is no onload support for stylesheets in most modern browsers. There is a solution I found with a little Googling.

Cited from: http://thudjs.tumblr.com/post/637855087/stylesheet-onload-or-lack-thereof

The basics

The most basic implementation of this can be done in a measely 30 lines of — framework independent — JavaScript code:

function loadStyleSheet( path, fn, scope ) {
var head = document.getElementsByTagName( 'head' )[0], // reference to document.head for appending/ removing link nodes
link = document.createElement( 'link' ); // create the link node
link.setAttribute( 'href', path );
link.setAttribute( 'rel', 'stylesheet' );
link.setAttribute( 'type', 'text/css' );

var sheet, cssRules;
// get the correct properties to check for depending on the browser
if ( 'sheet' in link ) {
sheet = 'sheet'; cssRules = 'cssRules';
}
else {
sheet = 'styleSheet'; cssRules = 'rules';
}

var interval_id = setInterval( function() { // start checking whether the style sheet has successfully loaded
try {
if ( link[sheet] && link[sheet][cssRules].length ) { // SUCCESS! our style sheet has loaded
clearInterval( interval_id ); // clear the counters
clearTimeout( timeout_id );
fn.call( scope || window, true, link ); // fire the callback with success == true
}
} catch( e ) {} finally {}
}, 10 ), // how often to check if the stylesheet is loaded
timeout_id = setTimeout( function() { // start counting down till fail
clearInterval( interval_id ); // clear the counters
clearTimeout( timeout_id );
head.removeChild( link ); // since the style sheet didn't load, remove the link node from the DOM
fn.call( scope || window, false, link ); // fire the callback with success == false
}, 15000 ); // how long to wait before failing

head.appendChild( link ); // insert the link node into the DOM and start loading the style sheet

return link; // return the link node;
}

This would allow you to load a style sheet with an onload callback function like this:

loadStyleSheet( '/path/to/my/stylesheet.css', function( success, link ) {
if ( success ) {
// code to execute if the style sheet was loaded successfully
}
else {
// code to execute if the style sheet failed to successfully
}
} );

Or if you want to your callback to maintain its scope/ context, you could do something kind of like this:

loadStyleSheet( '/path/to/my/stylesheet.css', this.onComplete, this );

How to load JavaScript CSS files in partial view

The solution obtained:

   $(document).on("focusin",".Date", function () {
$(this).datepicker({
dateFormat: "yy/mm/dd",
isRTL: true,
showButtonPanel: true
});
});

add css:

.datepicker{z-index:1151 !important;}

Injecting a CSS stylesheet using Javascript

If the stylesheet is a separate resource, (You've confirmed in a comment that it is), you link it with link rel="stylesheet":

var link = document.createElement("link");
link.rel = "stylesheet";
link.href = "mystyle.css";
document.head.appendChild(link);
// Or document.querySelector("head").appendChild(link);
// But I don't think that's necessary on any vaguely-modern browser

(Can't really do a live example of this one with Stack Snippets.)


If you have it as a string, you apply it with a style element:

var style = document.createElement("style");
style.appendChild(document.createTextNode("/*...style text here...*/"));
document.head.appendChild(style);

Live example: