1. 程式人生 > >Web前端離線快取應用

Web前端離線快取應用

		<script type="text/javascript">
			$(document).ready(function () {
				console.log('ready %o',new Date());
				var APP_START_FAILED = "I'm sorry, the app can't start right now.";
				function startWithResources(resources, storeResources) {

					// Try to execute the Javascript
					try {
						//eval(resources.js); v6
						insertScript(resources.js);
						setTimeout(function(){
							APP.applicationController.start(resources, storeResources);					
						},500);

					// If the Javascript fails to launch, stop execution!
					} catch (e) {
						alert(APP_START_FAILED);
						console.log('%o',e);
					}
				}
				function startWithOnlineResources(resources) {
					startWithResources(resources, true);
				}

				function startWithOfflineResources() {
					var resources;

					// If we have resources saved from a previous visit, use them
					if (localStorage && localStorage.resources) {
						resources = JSON.parse(localStorage.resources);
						startWithResources(resources, false);

					// Otherwise, apologize and let the user know
					} else {
						alert(APP_START_FAILED);
					}
				}

				// If we know the device is offline, don't try to load new resources
				if (navigator && navigator.onLine === false) {
					startWithOfflineResources();

				// Otherwise, download resources, eval them, if successful push them into local storage.
				} else {
					$.ajax({
						url: 'api/resources/',
						success: startWithOnlineResources,
						error: startWithOfflineResources,
						dataType: 'json'
					});
				}
				function insertScript (script) {
					var node=document.createElement('script');
					node.innerHTML=script;
					document.head.appendChild(node);
				}

			});
		</script>