Erik A. Hanson's Weblog

A Bookmarklet To Reload A Page’s CSS

Posted: February 28th, 2009    Tags: Javascript, Web development

Sometimes when I’m developing, I want to change some stylesheets and reload them without reloading the whole page. Often, I use Firebug or the Safari Web Inspector to play with individual attributes, but sometimes I have to edit the CSS files.

So I wrote a bookmarklet to reload the files. Here it is:

reload CSS

(Just drag that into your bookmarks bar. Tested in Safari and Firefox.)

It works by appending the letter “x” after a “?” at the end of each stylesheet reference. That causes the browser to reload the stylesheet. Here’s the code:

var links = document.getElementsByTagName("link");
for (var i = 0; i < links.length; i++) {
  if (links[i].rel === "stylesheet") {
    if (links[i].href.indexOf("?") === -1) {
      links[i].href += "?";
    }
    links[i].href += "x";
  }
}


5 Responses to “A Bookmarklet To Reload A Page’s CSS”

  1. grosser Says:

    simple + awesome, gotta try this tomorrow :)

  2. Paul Says:

    Very cool idea!
    I had a problem with this when I first tried it because the page I was testing had link elements with a “rel” attribute of “Stylesheet” instead of “stylesheet” (or both actually). So I switched the 3rd line to:
    links[i].rel.toLowerCase() === “stylesheet”

    And just a side note… I thought I’d give a try to rewriting this using Prototype since all of the sites I work on include Prototype already (of course this is no longer a generic solution this way). Here’s what I came up with:
    $$(‘link[rel=Stylesheet], link[rel=stylesheet]‘).each(function(link){link.href += (link.href.include(‘?’) ? ‘x’ : ‘?x’)});

    Thanks again for the great idea!

  3. Brandon Thomson Says:

    This is very useful, thanks very much… Actually I am surprised something like this is not in Firebug. I am using it to speed development of Conquer-on-Contact ;)

  4. Lawrence Barsanti Says:

    Very useful. Thanks.

  5. Wouter Bos Says:

    Works like a charm. Exactly what I was looking for.

Leave a Reply



(Comments are moderated to keep out spam. Please be patient.)