SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Member
    Join Date
    Apr 2006
    Location
    Provo, UT
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Prevent JavaScript File Caching in All Browsers

    Dear SitePoint,

    I'm currently using this method to refer to my JavaScript files:

    Code:
    <script type="text/javascript" src="filename.js"></script>
    While doing work for some clients I have made changes to the the JavaScript file referenced above. Because their browser has cached it, they end up getting errors on the page unless they hard refresh and get the new version of the file.

    Is there anyway to make the JavaScript file come down fresh if it has been modified since the last download?

    Thanks!

  2. #2
    ********* Ornithologist AtomicPenguin's Avatar
    Join Date
    May 2002
    Location
    Vancouver, BC
    Posts
    459
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Kirk,

    I believe the trick is to append a unique query string after the filename, like so:

    Code:
     <script type="text/javascript" src="filename.js?i=12345"></script>
    I remember reading that most browsers are smart enough to check the date of JS files and download it if there's a new one available. The big exception is IE. So, adding a query string like above (which you'd need to change anytime you change the JS file) fools IE into thinking it's a new file - so it downloads it again.

    All the best -
    A.P.

    generatedata.com - free JS/PHP/MySQL random test data generator.
    Form Tools - free PHP/MySQL form processor.

  3. #3
    SitePoint Member
    Join Date
    Apr 2006
    Location
    Provo, UT
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks AtomicPenguin, that seems to work. Here's my code:

    Code:
    <script type="text/javascript" src="filename.js?n=<?php echo rand(0,10000); ?>"></script>

  4. #4
    ********* Ornithologist AtomicPenguin's Avatar
    Join Date
    May 2002
    Location
    Vancouver, BC
    Posts
    459
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Excellent!

    And I'm sure you already realise this, but doing it that way will make the JS reloaded every time the user returns to the page. Just a warning!

    I'm doing exactly the same thing on a site of mine right now. I just use a global var which I change when I make changes to the JS files (which isn't all that often).

    All the best -
    A.P.

    generatedata.com - free JS/PHP/MySQL random test data generator.
    Form Tools - free PHP/MySQL form processor.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •