Cara menggunakan javascript load css

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

asked Feb 22, 2009 at 13:48


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');   = cssId;
    link.rel  = 'stylesheet';
    link.type = 'text/css';
    link.href = 'http://website.example/css/stylesheet.css'; = 'all';

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.


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"; = "screen,print";

document.getElementsByTagName( "head" )[0].appendChild( link );

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.

answered Feb 23, 2009 at 9:25


If you use jquery:

$('head').append('<link rel="stylesheet" type="text/css" href="style.css">');

answered Oct 28, 2015 at 9:13


3,2335 gold badges27 silver badges39 bronze badges


I guess something like this script would do:

<script type="text/javascript" src="/js/styles.js"></script>

This JS file contains the following statement:

if (!document.getElementById) document.write('<link rel="stylesheet" type="text/css" href="/css/versions4.css">');

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):

<script type="text/javascript">
if(document.createStyleSheet) {
else {
  var styles = "@import url(' http://server/stylesheet.css ');";
  var newSS=document.createElement('link');

answered Feb 22, 2009 at 13:56


1.2m492 gold badges4143 silver badges4884 bronze badges


Element.insertAdjacentHTML has very good browser support, and can add a stylesheet in one line.

    "<link rel=\"stylesheet\" href=\"path/to/style.css\" />");

answered Jun 12, 2018 at 17:22


2,1833 gold badges24 silver badges40 bronze badges

If you want to know (or wait) until the style itself has loaded this works:

// this will work in IE 10, 11 and Safari/Chrome/Firefox/Edge
// add ES6 poly-fill for the Promise, if needed (or rewrite to use a callback)

let fetchStyle = function(url) {
  return new Promise((resolve, reject) => {
    let link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.onload = function() { resolve(); console.log('style has loaded'); };
    link.href = url;

    let headScript = document.querySelector('script');
    headScript.parentNode.insertBefore(link, headScript);

answered Dec 2, 2016 at 14:01


14k7 gold badges64 silver badges61 bronze badges


Use this code:

var element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", "external.css");

answered Sep 27, 2017 at 4:17

In a modern browser you can use promise like this. Create a loader function with a promise in it:

function LoadCSS( cssURL ) {

    // 'cssURL' is the stylesheet's URL, i.e. /css/styles.css

    return new Promise( function( resolve, reject ) {

        var link = document.createElement( 'link' );

        link.rel  = 'stylesheet';

        link.href = cssURL;

        document.head.appendChild( link );

        link.onload = function() { 


            console.log( 'CSS has loaded!' ); 
    } );

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:

LoadCSS( 'css/styles.css' ).then( function() {

    console.log( 'Another function is triggered after CSS had been loaded.' );

    return DoAfterCSSHasLoaded();
} );

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

answered Jul 5, 2018 at 3:41

Arthur TarasovArthur Tarasov

3,3018 gold badges42 silver badges57 bronze badges


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.

answered Jan 25, 2012 at 8:04


2,3881 gold badge20 silver badges27 bronze badges

Have you ever heard of Promises? They work on all modern browsers and are relatively simple to use. Have a look at this simple method to inject css to the html head:

function loadStyle(src) {
    return new Promise(function (resolve, reject) {
        let link = document.createElement('link');
        link.href = src;
        link.rel = 'stylesheet';

        link.onload = () => resolve(link);
        link.onerror = () => reject(new Error(`Style load error for ${src}`));


You can implement it as follows:

window.onload = function () {
        .then(() => loadStyle("css/style.css"))
        .then(() => loadStyle("css/icomoon.css"))
        .then(() => {
            alert('All styles are loaded!');
        }).catch(err => alert(err));

It's really cool, right? This is a way to decide the priority of the styles using Promises.

To see a multi-style loading implementation see:

answered Nov 4, 2020 at 16:47

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:

answered Dec 12, 2010 at 12:01

Here's a way with jQuery's element creation method (my preference) and with callback onLoad:

var css = $("<link>", {
  "rel" : "stylesheet",
  "type" :  "text/css",
  "href" : "style.css"

css.onload = function(){
  console.log("CSS IN IFRAME LOADED");


answered Oct 22, 2014 at 18:18


1,06510 silver badges19 bronze badges

Below a full code using for loading JS and/or CSS

function loadScript(directory, files){
  var head = document.getElementsByTagName("head")[0]
  var done = false
  var extension = '.js'
  for (var file of files){ 
    var path = directory + file + extension 
    var script = document.createElement("script")
    script.src = path        
    script.type = "text/javascript"
    script.onload = script.onreadystatechange = function() {
        if ( !done && (!this.readyState ||
            this.readyState == "loaded" || this.readyState == "complete") ) {
            done = true
            script.onload = script.onreadystatechange = null   // cleans up a little memory:
            head.removeChild(script)  // to avoid douple loading
  done = false

function loadStyle(directory, files){
  var head = document.getElementsByTagName("head")[0]
  var extension = '.css'
  for (var file of files){ 
   var path = directory + file + extension 
   var link = document.createElement("link")
   link.href = path        
   link.type = "text/css"
   link.rel = "stylesheet" 

(() => loadScript('libraries/', ['listen','functions', 'speak', 'commands', 'wsBrowser', 'main'])) ();
(() => loadScript('scripts/', ['index'])) ();

(() => loadStyle('styles/', ['index'])) ();

answered Sep 6, 2016 at 12:08

Hasan A YousefHasan A Yousef

20.4k22 gold badges119 silver badges178 bronze badges


Here's a one line example, that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:

document.head.innerHTML += '<link rel="stylesheet" href="css/style.css">';

Most browsers support it. See the browser compatibility.

answered Sep 16, 2020 at 18:52


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.

answered Feb 22, 2009 at 14:04


7,5927 gold badges45 silver badges60 bronze badges

var elem = document.createElement('link');
elem.rel = ' stylesheet'
elem.href= 'style.css';//Link of the css file

answered Jul 31, 2020 at 10:36


I'd like to share one more way to load not only css but all the assets (js, css, images) and handle onload event for the bunch of files. It's async-assets-loader. See the example below:

<script src=""></script>
var jsfile = "";
var cssfile = "";
var imgfile = "";
var assetsLoader = new asyncAssetsLoader();
      {uri: jsfile, type: "script"},
      {uri: cssfile, type: "style"},
      {uri: imgfile, type: "img"}
    ], function () {
      console.log("Assets are loaded");
      console.log("Img width: " + assetsLoader.getLoadedTags()[imgfile].width);

According to the async-assets-loader docs

answered Nov 26, 2019 at 18:42


7589 silver badges13 bronze badges

Answer from future. In 2022, we have import assertions api for import css file.

import mycss from "./style/mycss.css" assert { type: "css" };

Browser support: till september 2022, only chromium based browsers supported.

Read more at: v8 import assertions post

tc39 github t39 import assertions proposal

answered Sep 22 at 13:26

var fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet")
fileref.setAttribute("type", "text/css")
fileref.setAttribute("th:href", "@{/filepath}")
fileref.setAttribute("href", "/filepath")

I'm using thymeleaf and this is work fine. Thanks

answered Oct 21, 2014 at 4:45



document.getElementById("of head/body tag")
        .innerHTML += '<link rel="stylesheet" type="text/css" href="style.css">';


1,5992 gold badges12 silver badges20 bronze badges

answered Aug 10, 2020 at 20:04


This function uses memorization. And could be called many times with no conflicts of loading and running the same stylesheet twice. Also it's not resolving sooner than the stylesheet is actually loaded.

const loadStyle = function (src) {
    let cache = [];
    return function (src) {
        return cache[src] || (cache[src] = new Promise((resolve, reject) => {
            let s = document.createElement('link');
            s.rel = 'stylesheet';
            s.href = src;
            s.onload = resolve;
            s.onerror = reject;

Please notice the parentheses () after the function expression.

Parallel loading of stylesheets:

    // ...
]).then(() => {
    // do something

You can use the same method for dynamic loading scripts.

answered May 2 at 5:14


1,33618 silver badges29 bronze badges