[Javascript] Is there an easy way to reload css without reloading the page?


Answers

Possibly not applicable for your situation, but here's the jQuery function I use for reloading external stylesheets:

/**
 * Forces a reload of all stylesheets by appending a unique query string
 * to each stylesheet URL.
 */
function reloadStylesheets() {
    var queryString = '?reload=' + new Date().getTime();
    $('link[rel="stylesheet"]').each(function () {
        this.href = this.href.replace(/\?.*|$/, queryString);
    });
}
Question

I'm trying to make a live, in-page css editor with a preview function that would reload the stylesheet and apply it without needing to reload the page. What would be the best way to go about this?




I tested this on IE11, Chrome, Firefox and it works:

1.

<link id="theBoostrapTheme" type = "text/css" rel = "stylesheet" href = "Content/bootstrap-theme.min.css"/>

2.

<a role="menuitem" tabindex="-1" href="javaScript:void(0);" onclick="changeCurrentTheme('_Cerulean')">Cerulean</a>
  1. Code:

    function changeCurrentTheme(theNewThemeName) {
      $("#theBoostrapTheme").attr("href", "Content/bootstrap-theme.min" + theNewThemeName + ".css");
      }

In this case the theme files other than the original were named like this: bootstrap-theme.min_ …. .css. For example: bootstrap-theme.min_Cerulean.css




First, add an id (if not present) to your stylesheet link tags like so:

<link id="mainStyle" rel="stylesheet" href="style.css" />

Next, in Javascript (also utilizing jQuery) add the following function:

function freshStyle(stylesheet){
   $('#mainStyle').attr('href',stylesheet);
}

Lastly, trigger the function on your desired event:

$('#logo').click(function(event){
    event.preventDefault();
    var restyled = 'style.css'; 
    freshStyle(restyled);
});

By updating the value of the linked stylesheet, even if it's the same value, you force the client to look again; when it does, it'll see and (re)load the latest file.

If you're running into issues with cache, then try appending a random (psuedo) version number to your filename like this:

var restyled = 'style.css?v='+Math.random(0,10000);

Hope this helps. Dillen's examples above also work, but you can use this if you want to just target one or a set of stylesheets with minor adjustments.




Switching between Twitter Bootstrap Themes?

Use Kickstrap. You can install themes from basically anywhere, make your own, includes themes from Bootswatch and it uses Less.js client-side to easily recompile your changes each time.




pass a variable to the view, the variable holds the value of the filename of the stylesheet? As far as changing the style file when the user is in the same page... see this question: Is there an easy way to reload css without reloading the page?

<?php
$data['stylesheet_name'] = 'user1';

$this->load->view('viewname', $data);

/**
 * View File
 **/

<link rel="stylesheet" type="text/css" href="/css/user/<?= $stylesheet_name; ?>.css" />



One more jQuery solution

For a single stylesheet with id "css" try this:

$('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');

Wrap it in a function that has global scrope and you can use it from the Developer Console in Chrome or Firebug in Firefox:

var reloadCSS = function() {
  $('#css').replaceWith('<link id="css" rel="stylesheet" href="css/main.css?t=' + Date.now() + '"></link>');
};



Reload CSS stylesheets with javascript

In plain Javascript:

var links = document.getElementsByTagName("link");

for (var x in links) {
    var link = links[x];

    if (link.getAttribute("type").indexOf("css") > -1) {
        link.href = link.href + "?id=" + new Date().getMilliseconds();
    }
}

In jQuery:

$("link").each(function() {
    if $(this).attr("type").indexOf("css") > -1) {
        $(this).attr("href", $(this).attr("href") + "?id=" + new Date().getMilliseconds());
    }
});

Make sure you load this function after the DOM tree is loaded.