使用 onload 事件异步加载 JavaScript 的缓存问题

发布于 2024-09-18 12:44:41 字数 1183 浏览 8 评论 0原文

我目前正在尝试异步加载一些js文件,以便它们无法阻止网站的其余部分。 我主要遵循这里的描述:

Javascript

异步 阻止加载 javascript 文件这效果很好,但我现在遇到了这样的问题:即使我更改了内容,javascript 文件也会被缓存并保持缓存(而且执行 shift-reload 也没有任何帮助)。

我当前加载脚本的代码如下所示:

 (function() {
   function xx_async_load() {
     var xx = document.createElement('script');
     xx.type = 'text/javascript';
     xx.async = true;
     xx.src = 'http://myserver.de/myjs.js';
     var el = document.getElementsByTagName('script')[0];
     el.parentNode.insertBefore(xx, el);
   }

   if (window.addEventListener) {
     window.addEventListener('load', xx_async_load, false);
   } else if (window.attachEvent){
     window.attachEvent('onload', xx_async_load);
   }

 })();

如果我直接调用“xx_async_load”内的代码并更改 myjs.js,则更改会被识别,但如果我通过 onload 事件加载它,它始终会保持缓存并且改变的永远不会被识别。

有谁知道如何让浏览器识别缓存文件中的更改(问题出现在 Opera、FF 和 IE 中工作正常)?

编辑:如果我查看 Operas Dragonfly 的“网络”选项卡,甚至没有在重新加载缓存的 JS 文件时完成请求,似乎它是直接从缓存加载它,甚至没有检查服务器上的文件。

EDIT2:我将测试它在缓存中保留的时间。如果明天就消失了就好了。否则我仍然可以使用日期参数提出解决方法(因此接受该答案)。再次感谢。

I am currently trying to load some js files asynchronously, so that they are not able to block the rest of the website.
I mainly followed the descriptions found here:

Asynchronous Javascript

In terms of the non blocking loading of the javascript file this works great, but i got now the problem that the javascript file is cached and stays cached even if i change the content (also doing shift-reload does not help anything).

My current code of loading the script looks like the following:

 (function() {
   function xx_async_load() {
     var xx = document.createElement('script');
     xx.type = 'text/javascript';
     xx.async = true;
     xx.src = 'http://myserver.de/myjs.js';
     var el = document.getElementsByTagName('script')[0];
     el.parentNode.insertBefore(xx, el);
   }

   if (window.addEventListener) {
     window.addEventListener('load', xx_async_load, false);
   } else if (window.attachEvent){
     window.attachEvent('onload', xx_async_load);
   }

 })();

If i call the code inside "xx_async_load" directly and change the myjs.js, the changes are getting recognized, but if I am loading this through the onload event it always stays cached and the changed are never recognized.

Does anybody know a solution how I make the browser to recognize the changes in the cached files (problem appears in Opera, FF and IE work fine)?

EDIT: If i look at the "Network" tab of Operas Dragonfly, there isn't even a request done on reload for the cached JS file, it seems that it is directly loading it from cache without even checking against the file on the server.

EDIT2: I will test how long it stays in the cache. If its gone till tomorrow its fine. Else I can still propose the workaround with a date param (so accepting that answer). Thx again.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤君无依 2024-09-25 12:44:42

阅读 Apache Directives for cache-control ....

您可能希望在 apache.conf 文件或 .htaccess 文件中包含类似的内容

该示例将告诉浏览器缓存 JS 文件,并且直到检查新版本为止7天过去了

<Directory "C:/apache_htdocs">
    #
    # Enable caching for static files
    # A86400  = Access + 01 days
    # A604800 = Access + 07 days

    <FilesMatch "\.(js)$">
        ExpiresActive On
        ExpiresDefault                            A604800
        ExpiresByType application/x-javascript    A604800
        ExpiresByType application/javascript      A604800
        ExpiresByType text/javascript             A604800

        Header set Cache-Control "public, max-age=604800, pre-check=604800"
    </FilesMatch>
</Directory>

Read up on Apache Directives for cache-control ....

You probably want something like this in your apache.conf file or an .htaccess file

The example will tell the browser to cache the JS file, and not check for a new version until 7 days have passed

<Directory "C:/apache_htdocs">
    #
    # Enable caching for static files
    # A86400  = Access + 01 days
    # A604800 = Access + 07 days

    <FilesMatch "\.(js)$">
        ExpiresActive On
        ExpiresDefault                            A604800
        ExpiresByType application/x-javascript    A604800
        ExpiresByType application/javascript      A604800
        ExpiresByType text/javascript             A604800

        Header set Cache-Control "public, max-age=604800, pre-check=604800"
    </FilesMatch>
</Directory>
黒涩兲箜 2024-09-25 12:44:41

是的,这相当简单。

只需为您的 URL 提供一个随机参数,例如: URL = http://www.yoururl.com -> ; http://www.yoururl.com/?number=(random number)

这个这样您将始终拥有一个唯一的 url。该参数在加载时会被页面丢弃,因为它没有被使用,

请告诉我这是否有帮助。

Yes, this is fairly simple.

Just give a random parameter to your URL, like : URL = http://www.yoururl.com -> http://www.yoururl.com/?number=(random number)

this way you will always have a unique url. the parameter will be thrown away by the page when it is loaded because it is not used.

Let me know if this helped

寄居者 2024-09-25 12:44:41

解决此问题的一个好方法是计算文件内容的 md5(),然后将该值作为参数附加到 URL。这样,只要文件内容相同,文件就会不断被缓存。

另一种方法是使用 HTTP 标头控制脚本的缓存行为,例如 ETag 或降低最大缓存过期时间。

A good way to solve this problem is to calculate the md5() of the file contents, and then append that value to the URL as a parameter. That way the file keeps getting cached as long as the file contents is the same.

Another way is to control the caching behavior of the script with HTTP-headers, such as a ETag or lowering the maximum cache expiry time.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文