且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如果脚本已更新,如何刷新页面缓存?

更新时间:2023-12-04 22:59:52

我的回答涉及


  1. 一个php脚本,用于检查服务器上的选定文件是否有修改日期。

  2. 在html页面上,javascript通过jQuery getJSON从php获取数据。

  3. 然后它检查有关文件的localstorage数据,这个数据是如果没有通过html5 localstorage找到,则首先存储。

  4. 然后它比较localstorage和php jSON数据之间的日期。

  5. 如果服务器上有新文件,它会存储新日期而不是本地存储中的旧日期以供将来访问。

  6. 仅在找到较新版本的脚本时刷新。

  1. a php script that checks selected files on the server for modification date.
  2. on the html page, javascript gets the data from php via jQuery getJSON.
  3. Then it checks for localstorage data regarding the files, this data is first stored if none found via html5 localstorage.
  4. Then it compares dates between localstorage and php jSON data.
  5. If there are new files on the server, it stores the new dates instead of the old dates on the localstorage for future visits.
  6. Refreshes only if newer versions of the scripts are found.

下面是代码,这里是jsfiddle:[ ::: jsfiddle ::: ]

Below is the code, and here's the 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 ("d-m-Y", $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 *** snippet tool doesn't allow it, so this code might not function on ***.<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>