Reputation: 141
I need to reload css files after the user select his theme colors with colorpicker.
Into another question here i found this good solution :
/**
* 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);
});
}
my problem is that i have a google fonts linked into the pages
<link href='http://fonts.googleapis.com/css?family=Varela+Round' rel="stylesheet">
and in console i recieve this error :
Failed to load resource: the server responded with a status of 400 (Bad Request)
http://fonts.googleapis.com/css?reload=1397489335832
The other css stored into my server are reloaded well.
e.g. <link href="css/style.css" rel="stylesheet" type="text/css" />
How i can "separate" the stylesheet google from the others ?
Upvotes: 1
Views: 1822
Reputation: 9272
You can test for the google stylesheet link easily enough:
var googleUrl = new RegExp('fonts.googleapis.com/css\\?family=Varela\\+Round');
$('link[rel="stylesheet"]').each(function () {
if (googleUrl.test(this.href)) {
continue;
}
However, the root problem is that your reloadStylesheets
function is too aggressive in replacing the queryString. Instead of blindly replacing everything after the question mark with your new reload
parameter, you should be more precise. That way, if you ever load a local stylesheet where the query string is important (e.g., a server-generated style sheet with only a subset of styles for mobile), you don't break your page with the script.
This will also obviate the need to exclude the Google stylesheet, but since it's unlikely that is going to change, you should continue to exclude it and let it load from browser cache.
Upvotes: 0
Reputation: 951
Your link to the fonts is http://fonts.googleapis.com/css?family=Varela+Round, therefore your reload link should be http://fonts.googleapis.com/css?family=Varela+Round&reload=1397489335832
You need to update your function to take into account cases where there is already a parameter in the URL.
function reloadStylesheets() {
var queryString = 'reload=' + new Date().getTime();
$('link[rel="stylesheet"]').each(function () {
if(this.href.indexOf('?') !== -1){
this.href = this.href + '&' + queryString;
}
else{
this.href = this.href + '?' + queryString;
}
});
}
Upvotes: 1