17

I want to reload all CSS stylesheets in a html page via javascript, without reloading the page.

I need this only while developing to reflect css changes without refreshing the page all time.

A possible solution is to add a ?id=randomnumber suffix to the css hrefs with javascript, but I don't want to do that.

I want to reload the stylesheet some way, without changing it's url, and the browser will decide if it needs to load a new version of that css or not (if server responds with a 304 - Not modified).

How to accomplish this?

Christoph
  • 50,121
  • 21
  • 99
  • 128
Tamás Pap
  • 17,777
  • 15
  • 70
  • 102
  • You might be interested in this [question](http://stackoverflow.com/questions/2024486/is-there-an-easy-way-to-reload-css-without-reloading-the-page) answers. – Eric Dec 05 '12 at 10:37
  • http://stackoverflow.com/questions/2024486/is-there-an-easy-way-to-reload-css-without-reloading-the-page this topic is quite related with your question. hope it helps – wandarkaf Dec 05 '12 at 10:38
  • try an ajax head-request and if the content has been modified load the whole css. – Christoph Dec 05 '12 at 14:36

5 Answers5

13

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.

Dillen Meijboom
  • 963
  • 7
  • 13
  • Of course! This is Javascript a client-side scripting language which is executed by your browser and thus won't reload the current page. The CSS pages will be reloaded. – Dillen Meijboom Dec 05 '12 at 10:40
  • Thank you Dillen, but I don't want to change link's href as I pointed out: 'without changing it's url'. I want the browser to decide if a new version needs to be loaded, or the cached version is the latest based on server response. – Tamás Pap Dec 05 '12 at 10:41
  • O sorry I misread your question! The point is when you don't add a random id or something the cache is ALWAYS loaded. EDIT: What you could do is make an Ajax request which returns the new CSS content en check it with the current CSS content. Based on this you can either reload or not reload the CSS page. – Dillen Meijboom Dec 05 '12 at 10:43
  • Since this is tagged `jQuery`, you could use jQuery to find the relevant `` tags, rather than checking for the existance of `.css` in the href attribute, which isn't necessarily a good indicator. It's perfectly valid to have ``. Plus, you're calling `getElmeentsByTagName` *way* too many times. Instead, use `$('link[rel=stylesheet]').each(...)`. – user229044 Dec 05 '12 at 20:26
  • Would like to point out that this fails in `"strict mode"` you need to declare `x` like `var x` – iConnor Sep 08 '13 at 18:50
  • No. But I will add "var x" ;) I also updated my answer with a jQuery version! – Dillen Meijboom Sep 11 '13 at 17:26
  • You forgot the opening bracket. `if ($(this).attr("type").indexOf("css") > -1) {` – user2226755 May 06 '15 at 09:13
6

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.

Charles
  • 50,943
  • 13
  • 104
  • 142
ChongFury
  • 161
  • 2
  • 3
3

There are much better ways to accomplish:

I need this only while developing to reflect css changes without refreshing the page all time.

One way is to use Grunt.js to watch for file changes, and then livereload the page.

The workflow is like this:

  • Save css document
  • Grunt watch sees the change
  • live reloads the css on the page

This can be chained with other Grunt functions, such as {sass|less|stylus} preprocessor compilation, to create a workflow like this:

  • save a Sass file
  • watch sees change
  • sass is compiled and minified to cdn location
  • new css is loaded onto the page

Other front-end automation resources:

Video from a Google employee: http://www.youtube.com/watch?v=bntNYzCrzvE

http://sixrevisions.com/javascript/grunt-tutorial-01/

http://aboutcode.net/vogue/

Michael Jasper
  • 7,962
  • 4
  • 40
  • 60
0

It's very simple in the GoogleChrome browser.

Press F12, click the cogwheel at the right bottom corner and select option Disable cache (while DevTools is open).

enter image description here

enter image description here

Warlock
  • 7,321
  • 10
  • 55
  • 75
0

An alternative for Grunt would be to use Prepros.

It also use a file watcher on your project folder, but for all your files. (js, css, php) and reload the page on every change. (+ If this is a small visual change like css, it wont refresh the page, it will make a smooth transition. (Works for colors, positioning, etc.))

Like Grunt, it compile and minify your files, and allow you to make a live preview on a specified url (not only localhost). (There are plenty more of functionalities)

Using a special port, it even synchronize events such as clic, mouse wheel, inputs, etc.

Humbertda
  • 364
  • 1
  • 6
  • 23