Updating web page caching when update my webpage - javascript

I want to create cache file for my webpage with php .But I want to change automatically when updating my webpage.How to solve these case.
Please say me these solution.

A good solution to this is to create a manifest file and include the resources you wish to cache in there. When you need to make a change, just alter the manifest and call
var appCache = window.applicationCache;
appCache.update(); // Attempt to update the user's cache.
...
if (appCache.status == window.applicationCache.UPDATEREADY) {
appCache.swapCache(); // The fetch was successful, swap in the new cache.
}
code and more info from: htmlrocks

Related

With offline file:/// protocol, I'm trying to store data in local storage through an iframe. How can I make this work, or is there a better way?

Background
In our company, we install our offline documentation topics (thousands of .htm files in a folder) on our users' computers. Users view our documentation offline through their browser using the file:/// protocol.
I have a banner that appears in the footer of each .htm file that asks users to decide whether we can track user analytics (via Application Insights). Once they make their choice, we don't show the banner.
My Goal and Overall Problem
My goal is to store their choice in the browser's local storage. I can do that just fine, but the problem is this:
These are offline .htm files. There is no website domain. So, the key and value for any local storage is stored only for the .htm file they are on at the time they make their choice. If they come back to a topic they made their choice on, then yes, my script can retrieve their choice. But if they navigate to another topic in our documentation system (another .htm file), the local storage key and value don't persist to those other topics, and my script doesn't know what they chose--so then the banner pops up again.
My Workaround Idea
I doubt this is the best approach, but not having a lot of experience and not knowing what else to try, necessity becomes the mother of invention.
Here's what I'm trying:
Have my local storage requests go through a single .htm file called storage.htm, thereby getting around the above problem by always having a single point of contact (storage.htm) with the local storage.
storage.htm loads via a blank iframe.
The iframe is tacked onto each .htm topic.
When a topic .htm loads, the iframe also loads and any functions inside it become (hopefully) available for use by my main script.
When users click on the banner, I send the choice as query parameters through my main script to the iframe's src.
storage.htm contains a parseQuery() function, and inside that function, it parses any query params and then does the actual localStorage.getValue(key) and localStorage.setValue(key,value) requests.
I then want to somehow force the iframe to refresh with those parameters and then call the parseQuery() function there from my main script.
My Code
From my main script:
Attempt 1:
I've tried the top-voted item from this thread,
How to check if iframe is loaded or it has a content?
but I get stuck inside the checkIfFrameLoaded() function, and it continues to loop through the check to see if the iframe is loaded. It never loads. I think it's because the contentWindow and/or contentDocument don't work with my offline files, so I won't bore you with that code.
Attempt 2:
This is what I'd like to do as it seems cleaner:
function doIframeStorage(type,key,value){
// We get a handle on the iframe's id of 'storage'.
let storage = document.querySelector('#storage');
const src = storage.getAttribute('src');
let query = src;
if (type==='get'){
query = src + `?type=${type}&key=${key}`;
} else if (type==='set'){
query = src + `?type=${type}&key=${key}&value=${value}`;
}
storage.src = query;
storage.addEventListener('load', (e) => parseQuery());
}
But I'm running into a problem where my parseQuery() function (from storage.htm) is always undefined:
Uncaught ReferenceError: parseQuery is not defined
Is it possible to load and access my parseQuery() function from my main script like I'm doing? If so, how? I thought the addEventListener would ensure it was loaded and therefore the parseQuery() function would then be available.
Or Is there a better way to do what I'm attempting?

HTML page using local data not showing changes to local data immediately

I am fairly new to web development. I am using HTML and Javascript, specifically the Jexcel Javascript library, to create a spreadsheet webpage. The spread sheet is sourced from a CSV file stored in the working directory of my project. The problem is, when I make changes to that CSV file, they do not show up in my project until I rename the file (and change the filepath in my code respectively). I suspect this has to do with the webpage caching the source CSV file, but I am not sure. How would I go about disabling caching/making my table source from the CSV file everytime? I am using Tomcat Web Server as well. Thank you.
The code that is sourcing my spreadsheet is the following:
<script>
$('#spreadsheet').jexcel({
allowInsertRow: false,
allowInsertColumn: false,
allowDeleteRow: false,
allowDeleteColumn: false,
csv : 'data/test.csv',
csvHeaders : true,
defaultColWidth : '200px',
});
</script>
When changes are made to test.csv I want those changes to show the next time the page is refreshed, but this is not currently happening.
Update: Restarting the Web Server does make the changes show up, so I believe this is a caching issue. I am using Java Servelets on the Server Side of my code.
Browser side caching of resources is a common issue.
To prevent it, the easiest way is to append a version hash to resource url to force reload when modified, so you still benefit of cache feature when file hasn't changed.
Without information about the languages you use on server side, it's very difficult to help you more.
Here is the fonction I generally use to generate resources url :
function assetv($path) {
$hash = 'undefined';
if (file_exists($path)) {
$hash = filemtime($path);
if (!$hash) {
$hash = md5_file($path);
}
}
return urlFromPath($path) . "?v=" . $hash;
}
Of course, the "urlFromPath" depends on your app ;-)
[EDIT]
The browser loads your csv file using an url (data/test.csv) that is "used as cache key" (approximately).
So to force reload when file was modified, you need to change the url, for instance with a version number parameter (file name doesn't changes) :
data/test.csv?v=1
data/test.csv?v=2
As server side only is aware of file state, you need to generate the versionned url on server side when building your HTML.
Finally, instead of managing a version number manually, you can use a "natural" attribute of the file, as it's last modification time or a hash of it's content.
Thank you all for the suggestions. Ultimately I found out the problem was due to the fact that the csv file I was sourcing my data from was in the project folder and Tomcat does not update changes to that file immediately. I solved this by reading the data from a file stored outside the working directory on my machine.

clear browser cache using jquery/Angularjs

I'm tying to clear the browser cache programmatically. I am doing this because i have deployed a new version of the application, but the browser gets old version and contents from cache. but i want to clear cache when browser gets new version and load the latest app from server.
I have also use location.reload(true); but it is not clearing cache just reload the current page.
You can clear browser cache by using version trick
For example,
<script src="custom.js?version=1.1.1"></script>
just add dummy version at the end of the file type.It will reload the code
You can't really clear the cache using Angular or JQuery. One way is to force your browser to request fresh resources.
One way to do this is using gulp-rev.
https://github.com/sindresorhus/gulp-rev
You can't do it from JavaScript. What you can do is following:
Append some variable string to the end of your content url. Example:
//example.com/script.js?version=1.0
or
var timestamp = new Date().getTime()
var url = "//example.com/script.js?ts=" + timestamp
This essentially fools the browser that the url you are trying to load is a new one and it skips looking for it in the cache.
Timestamp method does have a disadvantage that it doesn't make use of browser caching ever.
Also, make sure that your HTML file has proper content header set so that the html itself is not cached. Checkout How to control web page caching, across all browsers? for details on cache control headers.

Electron Reloading A Specific JS File On Command

I have recently been working on an Electron application which requires the storage of data in a javascript file which gets decrypted when the user logs in and displayed, and encrypted when the user logs out. However, while logged in, the user has the option to add data to the javascript file. Unfortunately though, when this process is complete, the new data is not displayed, despite using the exact same code in the initial display as in the reload. I am confident that this is due to the javascript file needing to be reloaded (file changes are not registered by Electron). I have tried the electron-reload module, but it seems to only allow for live reloads. I need a module or solution which allows me to do something like this.
var reload = require('some-reload-module');
reload.reload('../path/to/file.js');
...
Any solutions would be welcome as I have so far had no luck. Thank you in advance!
This is happening due to the fact that require caches its results in require.cache. To get around this, you can just delete the entry in the cache.
// Initially require the file; the result is cached.
require('../path/to/file.js');
// Delete the cached version of the module.
delete require.cache[require.resolve('../path/to/file.js')];
// Re-require the file; the file is re-executed and the new result is cached.
require('../path/to/file.js');

Force browser to reload all cache after site update

Is there a way to force the clients of a webpage to reload the cache (i.e. images, javascript, etc) after a server has been pushed an update to the code base? We get a lot of help desk calls asking why certain functionality no longer works. A simple hard refresh fixes the problems as it downloads the newly updated javascript file.
For specifics we are using Glassfish 3.x. and JSF 2.1.x. This would apply to more than just JSF of course.
To describe what behavior I hope is possible:
Website A has two images and two javascript files. A user visits the site and the 4 files get cached. As far as I'm concerned, no need to "re-download" said files unless user specifically forces a "hard" refresh or clears their cache. Once a site is pushed an update to one of the files, the server could have some sort of metadata in the header informing the client of said update. If the client chooses, the new files would be downloaded.
What I don't want to do is put meta-tag in the header of a page to force nothing from ever being cached...I just want something that tells the client an update has occurred and it should get the latest once something has been updated. I suppose this would just be some sort of versioning on the client side.
Thanks for your time!
The correct way to handle this is with changing the URL convention for your resources. For example, we have it as:
/resources/js/fileName.js
To get the browser to still cache the file, but do it the proper way with versioning, is by adding something to the URL. Adding a value to the querystring doesn't allow caching, so the place to put it is after /resources/.
A reference for querystring caching: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.9
So for example, your URLs would look like:
/resources/1234/js/fileName.js
So what you could do is use the project's version number (or some value in a properties/config file that you manually change when you want cached files to be reloaded) since this number should change only when the project is modified. So your URL could look like:
/resources/cacheholder${project.version}/js/fileName.js
That should be easy enough.
The problem now is with mapping the URL, since that value in the middle is dynamic. The way we overcame that is with a URL rewriting module that allowed us to filter URLs before they got to our application. The rewrite watched for URLs that looked like:
/resources/cacheholder______/whatever
And removed the cacheholder_______/ part. After the rewrite, it looked like a normal request, and the server would respond with the correct file, without any other specific mapping/logic...the point is that the browser thought it was a new file (even though it really wasn't), so it requested it, and the server figures it out and serves the correct file (even though it's a "weird" URL).
Of course, another option is to add this dynamic string to the filename itself, and then use the rewrite tool to remove it. Either way, the same thing is done - targeting a string of text during rewrite, and removing it. This allows you to fool the browser, but not the server :)
UPDATE:
An alternative that I really like is to set the filename based on the contents, and cache that. For example, that could be done with a hash. Of course, this type of thing isn't something you'd manually do and save to your project (hopefully); it's something your application/framework should handle. For example, in Grails, there's a plugin that "hashes and caches" resources, so that the following occurs:
Every resource is checked
A new file (or mapping to this file) is created, with a name that is the hash of its contents
When adding <script>/<link> tags to your page, the hashed name is used
When the hash-named file is requested, it serves the original resource
The hash-named file is cached "forever"
What's cool about this setup is that you don't have to worry about caching correctly - just set the files to cache forever, and the hashing should take care of files/mappings being available based on content. It also provides the ability for rollbacks/undos to already be cached and loaded quickly.
i use a no-cache parameter for this situations...
a have a string constant value like (from config file)
$no_cache = "v11";
and in pages, i use assets like
<img src="a.jpg?nc=$no_cache">
and when i update my code, just change the $no_cache value, and it works like a charm.

Categories

Resources