vbotio vbotio - 1 year ago 110
CSS Question

How to use a variable in my <links> href path in html

I'm versionating my css files to "force the browser" clear cache when I want.

<link rel="stylesheet" href="app/css/normalize.min.css?v=0.0.1">
<link rel="stylesheet" href="app/css/bootstrap.min.css?v=0.0.1">
<link rel="stylesheet" href="app/css/main.css?v=0.0.1">
<link rel="stylesheet" href="app/css/angular-chart.min.css?v=0.0.1">
<link rel="stylesheet" href="app/css/loading-bar.css?v=0.0.1">
<link rel="stylesheet" href="app/css/bootstrap-tour-standalone.min.css?v=0.0.1">

I have the following code, which is working well. My doubt is how to use a variable on it ?


<script> var version = '0.0.1'; </script>
<link rel="stylesheet" href="app/css/normalize.min.css?v=version">

I have tried something like this

var version = 0.0.1;
var srcpath = $(this).attr('href');
srcpath = srcpath.replace('version', version)

but it didnt work.

Answer Source

You can remove <link> elements from html, use $.holdReady() to hold .ready() handler from being called, request all resources using $.when() append <link> elements to document having version concatenated to path to resource, then call $.holdReady(false) to fire .ready() handlers when all <link> load events have been fired

Stylesheet load events

You can determine when a style sheet has been loaded by watching for a load event to fire on it; similarly, you can detect if an error has occurred while processing a style sheet by watching for an error event

var version = "?v=0.0.1";
// array of URL's to request
var links = ["app/css/normalize.min.css", "app/css/bootstrap.min.css", ..];


$.when.apply($, $.map(links, function(path) {
  return new $.Deferred(function(d) {
    var link = $("<link>", {href: path + version, rel: "stylesheet"})
    link.on("load", d.resolve);
.then(function() {

$(document).ready(function() {
  // do stuff when all `<link>` elements have been appended to `<head>`
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download