Как обновить кеш страницы, если сценарии были обновлены?

Я искал онлайн, чтобы найти решение для обновления кэша пользователей, если сайт обновлен. Не удалось найти ничего, кроме установки контроля версий на url файлов сценариев …

Я отвечаю на свой вопрос ниже и должен знать, является ли это совершенным кодом и может не обновляться в цикле. Пожалуйста, кто-нибудь может сообщить мне, нужны ли какие-либо изменения?

Мой ответ включает

  1. скрипт php, который проверяет выбранные файлы на сервере для даты модификации.
  2. на странице html javascript получает данные из php через jQuery getJSON.
  3. Затем он проверяет наличие локальных данных о файлах, эти данные сначала сохраняются, если ни один из них не найден через html5 localstorage.
  4. Затем он сравнивает даты между данными localstorage и php jSON.
  5. Если на сервере есть новые файлы, он сохраняет новые даты вместо старых дат в localstorage для будущих посещений.
  6. Обновляется, только если найдены новые версии скриптов.

Ниже приведен код, и вот jsfiddle: [ ::: jsfiddle ::: ]

Snippet is not allowing localStorage, instead try js fiddle: '/xepjcwsf/' 
 //Script to check (via php & javascript), if the files loaded into client's cache are old and refreshes the page if newer files found on the server. $(document).ready( function() { var newFileCacheDate; //uncomment: //$.getJSON('scripts/file_date.php', function(jsonData){ setTimeout(function(){ newFileCacheDate = {"css_1":"30-01-2015","css_2":"28-01-2015","css_3":"07-03-2015","js_1":"28-02-2015","js_2":"02-03-2015"}; //uncomment: //jsonData; var StoredData = getStorage(); var isUpdated = check_filedate(newFileCacheDate, StoredData); if(isUpdated) { console.log('files have been updated, isUpdated = true'); addNewStorage_and_refresh(newFileCacheDate); } //uncomment: //}).fail(function() { console.log( "Couldn't get the json data." ); }); }, 1000); function addNewStorage_and_refresh(newDates){ if(typeof(Storage) !== "undefined") { localStorage.setItem('filecache_date', JSON.stringify(newDates)); alert('filedate storage updated, refreshing'); location.reload(); } } function getStorage(){ if(typeof(Storage) !== "undefined") { var fileCacheDate, stored_FileDates; var dataToStore = { "css_1" : '30-01-2014', "css_2" : '28-01-2015', "css_3" : '07-03-2015', "js_1" : '28-02-2015', "js_2" : '02-03-2015' }; if (localStorage.getItem("filecache_date") === null) { localStorage.setItem('filecache_date', JSON.stringify(dataToStore)); console.log('filecache=null'); return dataToStore; } else if (localStorage.getItem("filecache_date") != null) { fileCacheDate = localStorage.getItem('filecache_date'), stored_FileDates = JSON.parse(fileCacheDate); console.log('filechache=present'); return stored_FileDates; } } } function check_filedate(newfile, oldfile){ var isItUpdated = false; $.each(oldfile, function (key, olddata) { if(Date.parse(process(olddata)) < Date.parse(process(newfile[key]))){ console.log('files have been updated = true'); isItUpdated = true; return false; } }); return isItUpdated; function process(date){ var parts = date.split("-"); return new Date(parts[2], parts[1] - 1, parts[0]); } //to convert and return date in standard format } }); /* THE PHP CODE ** Paste this PHP code as a separate "file_data.php" file for retrieving json data from ** ******************************************************************************************* <?php $filenames = array( "css_1" => 'file1_css.css', "css_2" => 'file2_css.css', "js_1" => 'file3_jscript.js', "js_2" => 'file4_jscript.js' ); $previousDate = array( "css_1" => '0', "css_2" => '0', "js_1" => '0', "js_2" => '0', ); foreach ($filenames as $jsonVar => $filename) { if (file_exists($filename)) { $mtime = filemtime($filename); $previousDate[$jsonVar] = date ("dmY", $mtime); } } echo json_encode($previousDate); ?> ******************************************************************************************* */ //Below code for demo purpose only. $(document).ready( function() { $('button#reset').on('click', function(){ localStorage.removeItem('filecache_date'); location.reload(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <!-- Check Console for Logs --> Check Console for Logs <br><br> If you were unable to see console log before page refresh, click on the reset button <br> (page will refresh after resetting localStorage data) <br><br> <button id="reset">Reset </button> <br><br> EDIT: Although jsfiddle allows localstorage, the stackoverflow snippet tool doesn't allow it, so this code might not function on stackoverflow.<br><br> <b style="color:red;">Uncaught SecurityError: Failed to read the 'localStorage' property from 'Window': The document is sandboxed and lacks the 'allow-same-origin' flag.</b>