Is there any way to clear cache programmatically in angular 7 application? - javascript

I have a component which lazy loads the images.For the first time when my page loads then at that time the images are displayed using lazy loading but if I refresh or reload or close and then open the tab then my images are pre loaded because it is now fetched from cache.Is there any way i can stop caching of my component in angular 7?

The cache is not being done by Angular but your browser. Once you load an image (and depending on the headers of the response) your browser will cache it to be able to load it faster the next time. This is usually a good approach.
Not sure why you don't want them to be cached but you have different options. Here you have a good read about HTTP caching: https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching This cache configurations for static assets are usually done by your web server and they depend on which webserver you are using (nginx, Apache, IIS, node, ...).
Another option is to append a random query string to your image URL. This HTTP cache system works by using the image URL as a resource key to identify it. Because of this reason you can do something like:
<img src="./yourimagefolder/yourimage.jpg?r=putherearandomstring">
In this way your image resource 'Id' will be different in each request. (You will need to change the 'putherearandomstring' string in the example with a different random string each time the page is loaded.

If this is just for development purposes, you can disable the cache in developer tools. I don't see a reason you would want to do this for a live site though? As you would be forcing the user to grab the images everytime they load the component which will reduce performance.

The problem with cache in an environment where custom software is updated frequently and some users are less savvy is that they will not automatically get critical client-side changes unless they are told specifically to refresh their cache. With all of the decorations in the index.html I have not yet found a reliable solution.

Related

How do you properly handle caching static web content?

Browsers cache static files. It's what they're designed to do. 99% of the time, that's a good thing. Until we as developers update that static content.
If a developer updates a javascript file, but a user's browser pulls the cached version of it, then:
Best case, it'll be missing some new functionality until the browser decides to update its cache
Worse case, if you also updated the html page to call a javascript function that didn't exist in the older version of the javascript file that the browser cached, your page breaks
As developers, we know to hit Ctrl+Shift+R, or Ctrl+F5, or open dev console, disable cache on the Network tab, and reload. But users don't know that.
What is the best practice to handle updates to static content?
Is it to make sure that when you add new functions to a .js file, you push out the update to production a few hours/days before you update the html to call that function in <script> tags, allowing browsers to updated their cache over that time?
Is it to not call javascript functions from HTML within <script> tags at all?
Is there a way to somehow force browsers to expire cache on a specific static file when you update it?
Something else?
Obviously disabling all caching on your site is possible, but not a realistic solution.
PS. I'm not using any kind of frontend framework - just raw javascript/jquery. If the situation is different with frontend frameworks, I'd love to heard about that too at a high level
If I understand correctly, you want the JavaScript file to be updated for the user when you update. you should use service work API to create a cache version for specific files or use the Google workbox library. click here. for service worker API click here
Some years ago location.reload(true) allowed bypassing the cache like CTRL / Command+Shift+R does. Only Firefox continues to support this feature by now, but the hard reload using javascript is no longer supported on chromium based browsers. (spec doesn't describe this feature (anymore))
This change was also discussed on this issue on github/Microsoft/TypeScript and several other places on the web.
jQuery uses a simple workaround to be compatible with almost everything. If you load something with jQuerys jQuery.ajax({ url, cache: false }), it appends a _=TIMESTAMP parameter to the url, which has a similar effect but may bloat the cache.
You can make use of the Entity tag header (ETag). Entity tags are similar to fingerprints and if the resource at a given URL changes, a new Etag value must be generated by the server, which is a similar behavior to the Last-Modified header. (caniuse:etag)
Entity tags in: Apache, IIS, nginx (nginx docs), nodejs
It is also possible to clear the sites cache with a Clear-Site-Data: "cache" header. (mdn, caniuse:clear-site-data)

Force caching of certain Javascript Library files (ie react.min.js, etc.) between pages?

Is it possible to force caching of certain Javascript Library files (ie react.min.js, etc.) when navigating between pages of a website that isn't a SPA?
Trying to look at the feasibility of a more componentized structure while not going full on SPA. The website I'm working on oftentimes has people visit a single page and then leave, but in cases where they do stick around, I don't want to have to have them reload each and every library on page load.
Background You Should Understand
There are literally thousands of articles on the web about this topic but here is a very good summary from Make Us Of's Everything You Need to Know About the Browser Cache.
The browser cache is a temporary storage location on your computer for files downloaded by your browser to display websites. Files that are cached locally include any documents that make up a website, such as html files, CSS style sheets, JavaScript scripts, as well as graphic images and other multimedia content.
When you revisit a website, the browser checks which content was updated in the meantime and only downloads updated files or what is not already stored in the cache. This reduces bandwidth usage on both the user and server side and allows the page to load faster. Hence, the cache is especially useful when you have a slow or limited Internet connection.
TL;DR
I don't know if your really looking for a way to force the browser to cache your files or if you just misunderstood how the cache works. In general the browser the visitor is using is the one that makes that decision and handles everything for you. If it sees that a resource is needed that was already accessed in the past it wont request it again, it'll just use its cache. So no, your libraries will not get re-loaded over and over. Just once.
Now if you really do need to force the browser to cache your files take a look at the answer(s) to Caching a jquery ajax response in JavaScript/browser. That should get you on a good path to a solution.

Force refresh doesn't work for Head JS

When scripts are loaded via Head JS I am unable to force the content to refresh using the Ctrl+F5 (or equivalent) keyboard shortcut.
The scripts cache correctly and the browser obeys the cache directives sent from the server (I'm using IIS 7.5). But unlike scripts tags included directly in the markup, I can't override the cache and force a refresh of the scripts loaded via Head JS.
I'm assuming this is a consequence of the way the scripts are loaded dynamically. I can live with this behaviour because forcing the refresh is only convenient during development, and I know of other ways I can force the content to be retrieved from the server.
I just wondered if anyone could explain why this is the case...
Update
This was never a problem for us in Live, because the cache directives for our static content were set appropriately. It was only ever a problem in Development and QA, The options left available to me were...
Configure all Dev and QA browsers to never cache content.
Configure the static content cache directives differently for Dev and QA environments - essentially setting MaxAge to something so small the content would always be expired. Only setting the correct MaxAge value in Live.
I went with the second option.
Dynamic script loading is not a part of the page loading proper. When you force refresh, the browser reloads the page and all resources referenced in its HTML and in referenced CSS files, but the scripts you load with head.js are not referenced in the page content and the browser has no way to figure out that head.js is going to create references to additional resources. At the point where these references are created, the browser is no longer refreshing the page and thus normal cache rules apply.
You can force reload of your scripts by appending unique query strings to their URLs (e.g. jquery.js?random=437593486394), but this will disable caching for all loads of your page, not just when you force refresh.
This is also a problem with require.js. Hopefully one of these work arounds will also apply to Head.Js
If using Chrome, open the developer tools panel on the Network tab, right click and choose 'Clear Browser Cache'
Do a bit of 'Cache-busting' by appending a datetime stamp to the query string for js resources
If your using IIS (which it looks like you are). Go to the HTTP Response Headers panel of your website, click Set Common Headers and set Expire Web content to immediately.
The latter is my preferred option for my development machine
I wouldn't say its a question of dynamic or not dynamic, when you inject a script it still causes the browser to make a HTTP request and apply whatever caching logic it applies.
Like mentioned above if you don't want scripts to be cached ..dynamic or static, it doesn't matter, you will usually have to append a timestamp in the form of a query string to it.
If you just want to see if you changes are working, do a force refresh in your browser ...usually CTRL+F5

Client side scripting to make changes in a file

Is there any client-side script that would be able to make changes to a file on the hosts computer? (Intention stated below)
I am creating a packaged app for chrome which can show some online data, and make it available even when offline.
There is a certain thing, for e.g. 'a webpage' i want to show/store (but i cannot get/read its contents due to it being on different origin). To show when online, i can use iframe, but am unable to preserve it for offline.
So i thought i could make an appcache (manifest within the application package) which will cache the file, and on press of an update button a script would run which would make some change to the manifest which would force the cached resource to be reloaded.
I searched a lot, but no results.
Any suggestions as to how it can be done. Or any other way to get it to work?
I don't think so. This could be a huge security problem if it existed.
If you had to, you could send an ajax request to the server to create a file it creates with the current prices, and add it to the appcache file.
Here is a link to another SO quesitob that has a list of APIs you could use to get your stock price.
Webservice to get stock quotes?

How can I ensure that the latest version of my javascript code is loaded for the client?

We have a client with thousands of users (who all use Internet Explorer) and a large amount of javascript files that enhance their user experience with our product.
The problem I'm having is that any time we update one of these scripts there is no way to know whether the client is seeing the latest version. What we're having to do is tell our client to do a hard refresh (ctrl+f5) before viewing any changes. Obviously this approach is not ideal.
I know that browsers cache based on the url, so one could use something like
<script src='myScript.js?ver=1.2'>
to get around the issue, but this is not an option for us.
I was hoping that there's some kind of header property or something similar that we could use to tell IE not to cache these scripts.
Any ideas?
You can also version the filename itself like jQuery does:
<script src='myScript-v1-2.js'>
Then, each time you revise the script, you bump the version number and modify the pages that include it to point to the name of the new script. This is foolproof vs. caching, yet still allows your viewers to receive the maximum benefit of caching and requires no server configuration changes for the .js file.
A full solution will typically include setting a relatively short cache lifetime for your host web page and then allow the various resources (stylesheet files, JS files, images, etc...) to have longer cache lifetimes for maximum caching. Anything that is fingerprinted can have a very long cache lifetime. See the reference that fabianhjr posted about for ways to set the cache lifetime of the host web page. It can be done in the web page itself (<meta> settings) or in the http headers via the server.
If you turn off caching for your script file (which would likely have to be done at the web server level for a script file) then all your viewers will lose the performance benefit of caching and you will lose the bandwidth and load-saving benefit of caching. If you use a common .JS file across many pages (a common design pattern), your viewers will see slower performance on every page.
Everything you need to know about cache http://www.mnot.net/cache_docs/
http://www.mnot.net/cache_docs/#CACHE-CONTROL <-- HTTP Headers

Categories

Resources