I'm trying to get the styles.css to not cache as the server is having issues with the css when it caches.
<script>
var numBAH = Math.floor(Math.random()*100);
</script>
<link href="styles.css+ numBAH +" rel="stylesheet" type="text/css" />
You can do this in the head of your document :
<script>
document.write('<link href="styles.css?r='+ Math.floor(Math.random()*100) +'" rel="stylesheet" type="text/css" />');
</script>
BUT :
you have great probabilities of finding two times the same number
you shouldn't generally avoid caching
Solutions I propose :
1) use (new Date()).getTime() instead of a random number
2) simply change the number when the version changes : styles.css?v=3 (without javascript)
If you have access to a server-side language it would be neater to render the link tag with a query string that is a hash of the entire content of the file. In that way, the cache invalidator ey will change only when the content of the file has actually changed.
After having seen the discussion that has followed, about how you never want to use cache, because it loads too quickly, I want to change my answer. Not to new Date(), but to: fix your page so that loading quickly is a desired result. If you're having specific problems with that, create a question that targets those problems, don't go directly for the lousy workaround.
Cache busting can be work without server-side rendering.
I tested recent versions of firefox, chrome and safari in both mobile and desktop, this code worked. (I'm Not sure about IE, though..)
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var numBAH = Math.floor(Math.random()*10000);
document.write('<LI' + 'NK HREF="./path/to/style.css?cacheBusting='+numBAH+'" rel="stylesheet">');
</SCRIPT>
</HEAD>
Related
Index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
var path = '/Scripts/';
document.write('<base href="' + path + '"/>');
</script>
</head>
<body>
<h1>WELCOME</h1>
<script src="test.js"></script>
</body>
</html>
test.js
console.log("Message from external script");
output
error.png
Here you can see, first it try to load the script from body tag before it get the actual base href path from script section.
Is there any way to get come out from this error? I mean not to load body script until base href set.
Once the base href set, it executed successfully.
Thanks.
The behavior you're seeing is (somewhat) browser-specific, and is related to your use of document.write to set the base href dynamically.
Chrome and Firefox try to load the page resources before applying the document.write, then updates those urls and tries again after you set the page <base>. Safari appears to not do this; it uses the inserted base href immediately. I have not tested other browsers.
(In all browsers the <base> tag, whether static or dynamic, needs to appear in the document before any links that depend on it.)
Other than the extra network request this seems to be harmless (see below), but you could avoid it by using a static <base> tag instead of dynamically writing one in, or by setting the full path on the <script> tag instead of depending on the <base>.
(re "harmless": I checked the case where a test.js exists both at the root level and inside the "/Scripts" directory. Dynamically inserting the "/Scripts/" base href did not cause both scripts to execute in Chrome: successful network requests for both test.js files were made, but only the code in "/Scripts/" was executed. So the browser makers have handled that edge case already. Good job, browser makers!)
You Can use this code
<script src="./scripts/test.js" type="text/javascript"></script>
I have made some changes on a live website (I know, not the best practice, but I was told to) and I'm having issues with caching. Every time I make a change to our CSS (SASS actually), I have to hit CTRL F5 to see the changes. That's not a problem for me, but the users are starting to complain of a broken website and many of them don't know how to clear the cache or use CTRL F5.
I have tried adding the following code, but it's not working.
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
I have also tried adding this script:
<script type="text/javascript">
$(document).ready(function(){
$('img').each(function(){
var date = new Date;
// add the current unix timestamp in microseconds to the the image src as a query string
this.src = this.src + '?' + date.getTime();
});
});
</script>
I don't know Javascript though, so I don't know how to use it properly. I have searched for answers and other people have said these things work for them, but they simply are NOT working for me. I am a designer and front-end developer, so PHP and Javascript are a bit beyond me.
Finally, I've also read about using version tags - ?v=x.x, but my issue is the site was coded by other developers and I have no clue how they are linking to our stylesheet (using SASS).
Any help would be great appreciated!
Thanks!
Ideally you'd use PHP to check the file's filemtime() (the time it was last modified), and use a technique called versioning to indicate it's a changed file, and to not load it from cache.
The resulting HTML would look something similar to this:
<link href="/your/css/file.css?ver=<?php echo filemtime('/your/css/file.css'); ?>" rel="stylesheet" type="text/css"/>
Call the external CSS file adding a random code as GET variable in PHP.
Something like this:
<script src="yourfileUpdated.css?<?php echo rand() ?> rel="stylesheet" type="text/css" />
Styles are added with wp_enqueue_style function. Search your theme, it is probably in functions.php.
Then use like this:
wp_enqueue_style('main-styles', get_template_directory_uri() . '/css/style.css', array(), filemtime(get_template_directory() . '/css/style.css'), false);
Read more here https://wordimpress.com/wordpress-css-and-js-cache-busting/.
I have a few small JQuery scripts in SharePoint that currently use hard-coded paths to include jquery itself and CSS, so they are a pain to move around.
I thought i'd use JS and document.write() to include the files using dynamically generated paths including the site root URL.
Problem: I have a piece of what I think is valid JS code, but IE10 spits it out with an "unterminated string" error. if I change the final '</script>' string to anything else it works ok (but of course doesn't result in valid html).
The code itself passes JSlint with a few comments about spacing. Javascriptlint.com generates a warning about "script tag must be empty if a path is specified", but I can fix that by setting the variable "imp" in two lines, firstly generating the linktag, then concatenating the script tag.
Code:
<script language="javascript">
var siteURL= L_Menu_BaseUrl;
var imp= '<link href="' + siteURL + '/SiteAssets/Path/my.css" rel="stylesheet" type="text/css"/>\n'
+ '<script language="javascript" src="' + siteURL + '/lib/js/jquery-1.9.1_min.js">' + '</script>\n';
</script>
I have been staring at this too long, it's probably something really simple. I'm just building an HTML string here but IE seems to be interpreting the final </script> tag, ignoring the fact that it's a literal string in quotes.
Any ideas?
IE seems to be interpreting the final </script> tag, ignoring the fact that it's a literal string in quotes
This is exactly what's happening. One solution is to use '</scr'+'ipt>'. Just break up the closing tag, so it's not interpreted as a close tag.
var imp= '<link href="' + siteURL + '/SiteAssets/Path/my.css" rel="stylesheet" type="text/css"/>\n'
+ '<script language="javascript" src="' + siteURL + '/lib/js/jquery-1.9.1_min.js">' + '</scr' + 'ipt>\n';
EDIT: You can also just do this
... + '<\/script>\n';
Thanks for the helpful comments. Having done more reading on this issue I came to the understanding that using document.write() is generally considered bad practice, or at least something to be avoided.
You can create the <link> and <script> tags entirely in JS code, but that ends up being pretty verbose. I also found it added a layout glitch to my page as the various bits of code wrote the tags that loaded JQuery and the CSS and THEN the browser could finally lay out the page correctly.
I ended up with a hybrid approach, using HTML tags to load the default (production site) location of the dependency files, but then having the script tweak the file paths for the dev site (where a slight layout delay is tolerable).
The result looks like-
<link id="MyCSS" rel="stylesheet" type="text/css" href="/sites/live/SiteAssets/Path/my.css"/>
<script id="JQ" language="javascript" src="/sites/live/lib/js/jquery-1.9.1_min.js"></script>
<script language="javascript">
/*
* Paths for dev / debug
*/
var siteURL= L_Menu_BaseUrl;
if( siteURL != "/sites/live" ) {
document.getElementById("MyCSS").href=
siteURL + "/SiteAssets/Path/my.css";
document.getElementById("JQ").src=
siteURL + "/lib/js/jquery-1.9.1_min.js";
}
</script>
My web application target to major Smartphones and I need to change the CSS file according to device (if there are issues in the UI need to hit them), and I’m planning swap CSS using following jQuery. Just want to know whether is it a best practice and good in performance?
<link rel="stylesheet" href="basic.css" type="text/css" class="cssLink" />
<link rel="stylesheet" href="general.css" type="text/css" />
<script type="text/javascript">
$(document).ready(function() {
// css file based on the device
var controlCss;
// get the device agent and conver to lover case
var deviceAgent = navigator.userAgent.toLowerCase();
if(deviceAgent.match(/android/i)){
controlCss = "android.css";
$(".cssLink").attr("href", controlCss);
}
else if(deviceAgent.match(/webso/i)){
controlCss = "webOS.css";
$(".cssLink").attr("href", controlCss);
}
else if(deviceAgent.match(/iphone/i)){
controlCss = "iphone.css";
$(".cssLink").attr("href", controlCss);
}
else if(deviceAgent.match(/ipod/i)){
controlCss = "ipad.css";
$(".cssLink").attr("href", controlCss);
}
else if(deviceAgent.match(/blackberry/i)){
controlCss = "bb.css";
$(".cssLink").attr("href", controlCss);
}
else {
controlCss = "basic.css";
$(".cssLink").attr("href", controlCss);
}
});
</script>
1.Is it best practice?
Depends on what you think of as best practice, also what best practice is in the context of your application and your company. One thing this makes me think about is: Can you guarantee all your pages will be using jQuery? If so then I think this is a good approach to achieve what you are after. An alternative would be to do this server-side, that would guarantee best-performance but there may be other reasons why you dont want to do this (maybe you dont have access to server-side code, or you want to maintain most of the functionality in the hands of front-end programmers).
2.Is it good in performance?
The short answer is no. On top of needing the 100K+ payload of jQuery to inject the CSS on the page. The way you've approached the problem at the moment is to wait for the whole page (and all dependencies) to load before adding styles to it. This will create a noticeable 'jump' between when the page gets displayed at first (without styles) and when the styles get loaded and everything moves around.
Loading the CSS server-side will get rid of this, but I think you can still do this in the UI and keep the majority of your code-base in JavaScript which will make it easier to maintain. In order to do this, remove the bit where you wait for the document to be loaded before calling up your CSS file:
<link rel="stylesheet" href="basic.css" type="text/css" class="cssLink" />
<link rel="stylesheet" href="general.css" type="text/css" />
<script type="text/javascript">
// No need to wait for document to load
// $(document).ready(function() {
// css file based on the device
var controlCss;
// get the device agent and conver to lover case
var deviceAgent = navigator.userAgent.toLowerCase();
if(deviceAgent.match(/android/i)){
controlCss = "android.css";
$(".cssLink").attr("href", controlCss);
}
// etc..
// });
</script>
To further improve performance you could use a solution that does not depend on jQuery, instead of
$(".cssLink").attr("href", controlCss);
you could add #cssLink to the stylesheet <link> element and use the DOM to do the same:
document.getElementById("cssLink").setAttribute("href", controlCss);
This would make you code look as follows:
<link rel="stylesheet" href="basic.css" type="text/css" css="cssLink" id="cssLink" />
<link rel="stylesheet" href="general.css" type="text/css" />
<script type="text/javascript">
// .. blah blah ..
if(deviceAgent.match(/android/i)){
controlCss = "android.css";
// use a solution that does not need jQuery
document.getElementById("cssLink").setAttribute("href", controlCss);
}
// etc..
</script>
This way you will remove the dependency on the 100K plus payload of jQuery before you can apply your stylesheets to the page.
UPDATE:
It is also possible to apply CSS rules based on screen size rather than device.
Have you had a look at #media queries?
I've noticed for quite a long time that strange domains such like jsev.com, cssxx.com appered in my firefox status bar from time to time, I always wonder why so many web pages contains resources from these strange domains. I googled it, but found nothing. I guess it's some kind of virus which infect the servers and insert the code. Here is a sample taken from page header of http://www.eflorenzano.com/threadexample/blog/:
<script language="javascript" src="http://i.jsev.com./base.2032621946.js"> </script>
<body onmousemove="return fz3824();">
<LINK REL="stylesheet" TYPE="text/css" HREF="http://i.cssxx.com./base2032621947.css">
<SCRIPT LANGUAGE="JAVASCRIPT" SRC="http://i.js.com./base2032621947.js"></SCRIPT>
<SCRIPT LANGUAGE="JAVASCRIPT">
function getuseragnt()
{ var agt = navigator.userAgent.toLowerCase();
agt = agt.replace(/ /g, "");
return agt;
}
document.write("<LINK REL='stylesheet' TYPE='text/css' HREF='http://i.css2js.com./base.css" + getuseragnt() + "_2032621947'>")
</SCRIPT>
edit: I am on a debian box, only on firefox I see this code, I just tried opera, this code doesn't appear in opera, really strange, never heard of firefox having such problems.
This happens if you are using one of Princeton university's CoDeeN project proxy servers. CoDeeN is an academic testbed content distribution network. When you browse a web page using CoDeeN proxy it injects some HTML code to the site's original HTML and redirects requests sent to pseudo adresses to the project's servers.
Some of the pseudo addresses are:
http://i.cssxx.com./base0877861956.css | i.cssxx.com.
http://i.jsev.com./base.0877861955.js | i.jsev.com./
http://i.html.com./base0877861956.html | i.html.com.
http://i.js.com./base0877861956.js | i.js.com./
http://i.css2js.com./base.css | i.css2js.com.
Some or all CoDeeN's proxy servers appear as anonymous proxy servers list.
CoDeeN project page: http://codeen.cs.princeton.edu/
It may be a browser worm installed on your machine. Should scan entire system.
I see nothing unusual about that page. Check your system. Here's the code I received:
<head><title>Tutorial 2</title>
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.4.1/build/reset/reset-min.css">
<link rel="stylesheet" type="text/css" href="http://media.eflorenzano.com/css/example2.css">
<script type="text/javascript" src="http://media.eflorenzano.com/js/jquery-1.2.2.min.js"></script>
<script type="text/javascript" src="http://media.eflorenzano.com/js/jquery.form.js"></script>
<script type="text/javascript">
var _POSTER = '';
var _FORM = '<textarea id="id_comment" rows="10" cols="40" name="comment"></textarea>';
var _FORM_URL = '/threadexample/threadedcomments/comment/9/1/json/';
var _REGISTER_URL = '/threadexample/register';
var _CHECK_EXISTS_URL = '/threadexample/check_exists';
var _LOGIN_URL = '/threadexample/login';
var _IS_FOCUSED = null;
var _ARROW_IMG_BASE = 'http://media.eflorenzano.com/img/arrow_';
var _VOTE_BASE = '/threadexample/vote/';
</script>
<script type="text/javascript" src="http://media.eflorenzano.com/js/example2.js"></script>
</head>
DNS poisoning?
I agree with Mediashakers
That cause you're using CoDeeN project proxy servers
Try use no proxy, it will see the difference
That could very well be the case, as this does kinda look like some shady code. What if you use a different computer, does the source look the same?
Hm ... No solution here, but as a datapoint: It doesn't look at all like that for me (Firefox 3.0.3, in Gentoo Linux). I get the following interesting elements in the header:
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.4.1/build/reset/reset-min.css">
<link rel="stylesheet" type="text/css" href="http://media.eflorenzano.com/css/example2.css">
<script type="text/javascript" src="http://media.eflorenzano.com/js/jquery-1.2.2.min.js">
<script type="text/javascript" src="http://media.eflorenzano.com/js/jquery.form.js">
[...]
<script type="text/javascript" src="http://media.eflorenzano.com/js/example2.js">
This looks fairly clean to me; four references to resources on the same server, plus one CSS from what looks like Yahoo!. Strange, I wonder why it looked so different for you. Hopefully some true web wizard can shed some light on that.
Also, I notice that all the weird-looking URI:s have domain names that end in a period, which I don't think is even legal. I Googled it, and found some old Digg thread, but was unable to locate the exact comment that mentioned the weird-looking URI:s. Strange.