How to check if jQuery is already in cache?

2020-03-01 07:09发布

Is there anyway to check on a client if jQuery was loaded before from a CDN? I mean to have code like this:

if (jQuery.isLoadedFromCDN)
//DoNothing
else
//load from internal resource

NOTE that I don't want to check that jQuery is loaded, but specifically if it was loaded from a CDN.

The context is that I have an internal LAN web app that uses jQuery, loading jQuery from the LAN is definitely faster but if it already was downloaded before from a CDN (which is probably the case) then I just want to use that otherwise I want to get it from our internal resource not the cdn. The bandwidth saving is definitely not huge, but I am more curious to know if that's technically possible.

3条回答
成全新的幸福
2楼-- · 2020-03-01 07:38

I'm guessing you're checking to see if jQuery was loaded from the Google Libraries API?

Your browser will cache jQuery whether it's from the CDN or from your LAN. If it's already in the cache from a previous retrieval from the CDN, it'll load faster than from your LAN. If it's not already in your cache from either a previous visit to your site, or another site using the same CDN, it'll only need to load once: subsequent visits will load from the cache.

Splitting the URL for jQuery between the CDN and your LAN will just cause two copies to get cached. Let the browser cache do what it was meant to do. :)

查看更多
来,给爷笑一个
3楼-- · 2020-03-01 07:46

to my knowledge, that's not really possible. 2 things jump to mind however that can help you:

  1. Use Etags: Identify your resources on the webserver side. This way, your browser does that work for you: identify if a resource is already loaded, regardless from the domain it was loaded from
  2. If you really want to know which domain jQuery was loaded from, you can do dummy AJAX requests. You can only do AJAX requests from the same domain your library was loaded from (except ofcourse when doing a JSONP request). So if your jQuery was loaded from your LAN resource, you will get trplies to AJAX requests to your LAN webserver, and that rules out the CDN.

Hope it helps,

Bart

查看更多
混吃等死
4楼-- · 2020-03-01 07:56

This should do it:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.4.js"%3E%3C/script%3E'))</script>

You need to adapt the path for the fallback, which should be located at your domain.

查看更多
登录 后发表回答