Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

javascript - Dynamically Trigger HTML5 Cache Manifest file?

I am using the new cache manifest functionality from HTML5 to cache my web app so it will work offline. The content is cached automatically when the page is loaded with the following html element:

<html lang="en" manifest="offline.manifest">

This works fine. However, I want to give my users the option of whether they want the content cached offline. So, here is my question:

Is there any way to trigger that an application be cached at runtime, using JavaScript, and not have it automatically done when the page is loaded.

For example, something like this (using jquery):

----------------index.html--------------

<head>
 <meta charset="utf-8" />

 <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script> 
 <script type="text/javascript" src="Main.js"></script> 

</head>
<body>

 <button id="cacheButton">Cache Page</button>

</body>
</html>

---------Main.js---------

$(document).ready(
 function()
 {
  $('#cacheButton').click(onCacheButtonClick);
 }
)

function onCacheButtonClick(event)
{
 console.log("Setting Offline Manifest");
 $('#htmlRoot').attr("manifest","offline.manifest");
}

-------------offline.manifest-------------

CACHE MANIFEST

#version .85

#root
index.html
scripts/main.js

#jquery assets
http://code.jquery.com/jquery-1.4.4.min.js

Basically, when the button is clicked, I dynamically set the manifest attribute of the html element. This works (in the sense the element is set), but it does not cause the browser to then cache the page.

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You dynamically trigger caching by adding an iframe that points to an empty page containing the actual cache manifest.

offline.html:

<!DOCTYPE html>
<html manifest="offline.appcache">
<head>
    <title></title>
</head>
<body>
</body>
</html>

Make sure to add index.html to the cache manifest. Then just add something like:

<iframe src="offline.html" width="0" height="0">

to document.body dynamically to trigger caching.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...