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

时间:2015-05-06 10:59:51

标签: javascript php css html5 browser-cache

如果网站已更新,我在线搜索以找到刷新用户缓存的解决方案。除了在脚本文件的URL上设置版本控制之外,找不到任何东西......

我正在回答下面的问题,并且需要知道这是否是一个完美的代码,并且可能无法在循环中保持刷新。如果需要修改,有人可以告诉我吗?

1 个答案:

答案 0 :(得分:1)

我的回答涉及

  1. 一个php脚本,用于检查服务器上的选定文件是否有修改日期。
  2. 在html页面上,javascript通过jQuery getJSON从php获取数据。
  3. 然后它检查有关文件的本地存储数据,如果没有通过html5 localstorage找到,则首先存储该数据。
  4. 然后它比较localstorage和php jSON数据之间的日期。
  5. 如果服务器上有新文件,它会在localstorage上存储新日期而不是旧日期,以供将来访问。
  6. 仅在找到较新版本的脚本时刷新。
  7. 下面是代码,这里是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 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>