In Javascript how do you check if the User has a C

2019-09-05 04:09发布

Possible Duplicate:
How to detect when XHR returns a cached resource?

I built an auto loader that only loads a javascript file if it has not already been loaded on this page using jquery with:

$.getScript();

I first check if the functions exist and if they do not I load them. However, this is unable to account for the browsers cache, I was hoping I might be able to figure out how.

One thing I would like to add to it is to see if the user already has the file saved in their browsers cache. Is it possible to check if a file from your server has already been cached on the users browser, so that I can skip making the call to the server at all?

2条回答
Rolldiameter
2楼-- · 2019-09-05 04:37

The cache works transparently. If you request a file and the file exists in the user's cache, then the cached file will be used and there will not be an additional request to the server. The browser takes care of that, so you don't have to worry about it for the case that you're describing.

.getScript by default disables this using timestamped query arguments, so you simply need to disable the cache bypass which getScript uses:

$.ajaxSetup({
  cache: true
});
查看更多
叛逆
3楼-- · 2019-09-05 04:38

Browser will determine whether to retrieve from server or not when request is made based on whether file is already in cache. jQuery will ad a timestamp so a new version is loaded each time. This can be turned off by setting cache:true

As for methods to check if you have already loaded in page so as not to load it again within your code you can do a variety of things.

  1. Add a class to element or body when script loads and check if class exists before making a new call.
  2. Set a variable flag withing the script and check for existence before making new call
  3. Check if a function within the script exists before making a new call
查看更多
登录 后发表回答