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?

3
  • You might be interested in this question answers. Commented Dec 5, 2012 at 10:37
  • stackoverflow.com/questions/2024486/… this topic is quite related with your question. hope it helps Commented Dec 5, 2012 at 10:38
  • try an ajax head-request and if the content has been modified load the whole css. Commented Dec 5, 2012 at 14:36

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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.
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.
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.
Since this is tagged jQuery, you could use jQuery to find the relevant <link> 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 <link rel="stylesheet" href="my-styles" />. Plus, you're calling getElmeentsByTagName way too many times. Instead, use $('link[rel=stylesheet]').each(...).
Would like to point out that this fails in "strict mode" you need to declare x like var x
|
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.

1 Comment

Instead of Math.random, you can use the current time: var restyled = 'style.css?v=' + new Date().getTime();
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/

1 Comment

This is the way to go!
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

3 Comments

But does that reload the stylesheets?
Yes. This option tells browser to reload stylesheets when your DevTools panel is opened.
@Bergi this option disables cache, so stylesheets and javascript files will be reloaded. I believe that FF and IE should have a same option.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.