Use ASP. NETMVC to build HTML5 offline web applications-

Source: Internet
Author: User
One of the main constraints of web applications is connectivity. Before HTML5 came, we wanted to explore the capabilities of browsers to make web applications as powerful and easy to use as desktop applications, but we were always disappointed with browsers. Although some browser cache technologies have appeared before ,...,. One of the main constraints of web applications is connectivity. Before HTML5 came, we wanted to explore the capabilities of browsers to make web applications as powerful and easy to use as desktop applications, but we were always disappointed with browsers. Although some browser caching technologies have already appeared, these caching technologies were not designed to allow web applications to run completely offline. Unfortunately, in fact, web applications using these technologies are prone to problems and difficult to use. HTML5 tries to use offline application cache Technology to fill the gaps in the browser's capabilities. This technology can make web applications work offline more reliably.

Why do web applications need to run offline?

To be honest, web applications on a desktop computer do not bring much benefits even if they can run completely offline, because desktop computers are always connected. What I expect to see in particular is how much benefit web applications on mobile devices can get from Offline Application cache technology.

In many places, mobile phone penetration continues to grow. If you can naturally bridge the gap of network disconnection, web applications in mobile browser will be more friendly to users.

In some specific scenarios, enabling the entire application to run offline means that we only need to create a cross-platform browser solution without creating multiple built-in applications.

Imagine that a salesman needs to display a product catalog to her customers anytime and anywhere. She can use any electronic device she wants. She needs to connect the device when browsing the product catalog for the first time, and then can browse it offline anytime, anywhere.

The application cache technology is not only available offline. We can use the application cache as a super cache for local storage resources to accelerate application startup. The updated resources on the server can be reloaded in the background thread. After loading, the old local resources are replaced and updated to the running application. This method is very suitable for heavyweight web applications on desktop computers.

Configuration File

To use the application cache, you do not need to write a large amount of code. You can define the resources to be used offline in a simple text file, which is called a manifest file.

Configuration File Format

A simple configuration file has the following format:

  1. CACHE MANIFEST
  2. # Version 1.0
  3. CACHE:
  4. /Home/index
  5. /Content/style.css
  6. /Scripts/main. js
  7. NETWORK:
  8. /Service/status
  9. FALLBACK:
  10. /Logo.png/logo_offline.png



You must place the cache manifest header in the first line of the configuration file.

A row starting with a digit # Is a comment row. This is usually used to explicitly modify the inventory file to notify the browser to update the cache. For example, this method is useful when you update an image without modifying the image name, because the browser does not detect that the image on the server has been updated.

Next, the configuration file contains the following three sections: CACHE, NETWORK, and FALLBACK. In the CACHE section, you can specify the resources to be cached. Resources that need to be downloaded from the server all the time (even if disconnected) are specified in the NETWORK. If a large number of resources need to be downloaded from the server all the time, you can use the wildcard character (an asterisk *) in the NETWORK section. In the FALLBACK section, you can specify the standby resources that can be used offline.

The configuration file format is not very strict. The parts described above can be in any order and can even be used multiple times in a configuration file.

In the configuration file, you can use relative or absolute paths to locate resources. If you use a relative path, you must use the location of the inventory file as a reference to locate the resource.

Reference the inventory file

To bind the inventory file to an application, you need to add the manifest attribute to the html Tag. By default, each page that references the configuration file is cached. However, we recommend that you display the resources you want to cache in the inventory file. If a page is not specified in the list file or browsed online, it cannot be accessed offline, because the browser cannot know whether the page exists in the local cache.



Check cache status

By using the application cache API, we can check the application cache status. You can use the window. applicationCache attribute to query the current cache status. The value of this status attribute is a number between 0 and 5. Each number corresponds to a specific cache status.


You can use the setInterval function to quickly display status changes.

  1. SetInterval (function (){
  2. Console. log (window. applicationCache. status)
  3. },500 );



Event Processing

In addition to checking the cache status, we can also handle specific events.


Cache replacement

After the new cache is downloaded, it will not replace the old cache immediately, but will not be replaced until we notify the application to use the new cache. We can use swapCache to replace the old cache with the new cache by processing the updateready event. The updated resource can only be seen after the page is refreshed.

  1. Window. applicationCache. onupdateready = function (){
  2. Window. applicationCache. swapCache ();
  3. });



How can users know that your application can run offline?

As far as I know, no browser will notify users that the current application can run offline. However, we can notify users by ourselves: By listening to specific events cached by the application, we can notify users when the application has been able to work offline. We can even notify users of each stage of the application cache lifecycle.

The handling of application cache-related events is straightforward. One of the most useful events is the SS event. This event is triggered every time a resource is downloaded. It contains three very useful attributes. We can use these three attributes to display the download progress: lengthComputable, loaded, and total. First, we need to check the lengthComputable attribute to determine whether the loaded and total attributes are available. Then we use the loaded and total attributes to calculate the percentage progress of resource download.

  1. Window. applicationCache. onchecking = function (e ){
  2. UpdateCacheStatus ('checking for a new version of the application .');
  3. };
  4. Window. applicationCache. ondownloading = function (e ){
  5. UpdateCacheStatus ('downloading a new offline version of the application ');
  6. };

  7. Window. applicationCache. oncached = function (e ){
  8. UpdateCacheStatus ('application is available offline .');
  9. };

  10. Window. applicationCache. onerror = function (e ){
  11. UpdateCacheStatus ('Something went wrong while updating the offline version of the application. It will not be available offline .');
  12. };

  13. Window. applicationCache. onupdateready = function (e ){
  14. Window. applicationCache. swapCache ();
  15. UpdateCacheStatus ('the application was updated. Refresh for The changes to take place .');
  16. };

  17. Window. applicationCache. onnoupdate = function (e ){
  18. UpdateCacheStatus ('the application is also available offline .');
  19. };

  20. Window. applicationCache. onobsolete = function (e ){
  21. UpdateCacheStatus ('the application cannot be updated, no manifest file was found .');
  22. };

  23. Window. applicationCache. onprogress = function (e ){
  24. Var message = 'downloading offline resources ..';
  25. If (e. lengthComputable ){
  26. UpdateCacheStatus (message + Math. round (e. loaded/e. total * 100) + '% ');
  27. } Else {
  28. UpdateCacheStatus (message );
  29. };
  30. };



How can I check whether the browser is online or offline?

You need to know whether the browser is online or offline for the following reasons: Maybe it is because you want to notify the user that the browser is working offline, it may be because you want to disable some functions of the application when the network is disconnected, or because you want to use local storage technology to support offline user input, then, the text entered by the user is synchronized to the server during the launch. To meet these requirements, you can build your own infrastructure, or use open-source projects or third-party projects.

Detect online status

In principle, it should be very simple to check the onLine status. For example, under standard conditions, you can use the onLine attribute of a single piece of navigator to check whether the current browser is onLine.

  1. Console. log (navigator. onLine)



But in fact it is not that simple, because various browsers have different definitions of online and offline. For example, the Firefox browser of the old version updates the value of the onLine attribute only when the user displays the onLine or offline status switch, ignoring the actual network conditions. Aside from implementation inconsistency, It is not trivial to check the network connection status. For example, if your computer is connected, but your router has a problem, what status should you display?

A popular hack method is to check the status code of each AJAX request, and then roll back to the offline mechanism when the status code is unsuccessful.

Event Processing

If you want to do something when the browser changes the connection status, you can handle offline and online events. However, please note that, like checking the onLine attribute, there are similar issues with using these two events.

  1. Window. addEventListener ('offline', function (e ){
  2. Console. log ('offline ');
  3. }, False );
  4. Window. addEventListener ('online', function (e ){
  5. Alert ('online ');
  6. }, False );



Browser support

In addition to Internet Explorer, all mainstream modern browsers support offline web applications. Internet Explorer 10 also implements relevant specifications, but it is not yet released. On caniuse.com, you can view the support of each browser and its version for this specification.

For most implementations, the mainstream browsers are basically consistent. But in terms of storage quota and quota management (these two items are not defined in the Specification), there is a big difference between browsers. When testing your web application, you should consider this issue. browsers on mobile devices are very concerned about the cache size.

Use ASP. net mvc to generate and provide configuration files

Generate inventory file

ASP. net mvc can be used to create and provide configuration files. The simplest way is to make ASP. net mvc provide static text files. However, if we want to use the built-in ASP. net mvc feature to parse the route, or want to write code to dynamically manipulate the configuration file, we 'd better use the custom action result.

I name this custom action result as ManifestResult, which inherits from the FileResult class in the MVC framework. When the listfile service is provided, the 'text/cache-manifest 'MIME type should be used. I passed this string to the constructor of the parent class.

  1. Public class ManifestResult: FileResult
  2. {
  3. Public ManifestResult (string version)
  4. : Base ("text/cache-manifest "){}
  5. }



The ManifestResult class has four attributes, three of which correspond to three sections of the configuration file, and the other corresponds to the version number. The two attributes of the CACHE section and the NETWORK section are only string enumeration, and the attribute of the FALLBACK section is of the dictionary type, which is used to map resources to the resources specified by FALLBACK.

  1. Public class ManifestResult: FileResult
  2. {
  3. Public ManifestResult (string version)
  4. : Base ("text/cache-manifest ")
  5. {
  6. Version = version;
  7. CacheResources = new List ();
  8. NetworkResources = new List ();
  9. FallbackResources = new Dictionary ();
  10. }
  11. Public string Version {get; set ;}
  12. Public IEnumerable CacheResources {get; set ;}
  13. Public IEnumerable NetworkResources {get; set ;}
  14. Public Dictionary FallbackResources {get; set ;}
  15. }



To output the formatted inventory file to the response stream, you must override the WriteFile method.

  1. Protected override void WriteFile (HttpResponseBase response)
  2. {
  3. WriteManifestHeader (response );
  4. WriteCacheResources (response );
  5. WriteNetwork (response );
  6. WriteFallback (response );
  7. }
  8. Private void WriteManifestHeader (HttpResponseBase response)
  9. {
  10. Response. Output. WriteLine ("cache manifest ");
  11. Response. Output. WriteLine ("# V" + Version ?? String. Empty );
  12. }
  13. Private void WriteCacheResources (HttpResponseBase response)
  14. {
  15. Response. Output. WriteLine ("CACHE :");
  16. Foreach (var cacheResource in CacheResources)
  17. Response. Output. WriteLine (cacheResource );
  18. }
  19. Private void WriteNetwork (HttpResponseBase response)
  20. {
  21. Response. Output. WriteLine ();
  22. Response. Output. WriteLine ("NETWORK :");
  23. Foreach (var networkResource in NetworkResources)
  24. Response. Output. WriteLine (networkResource );
  25. }
  26. Private void WriteFallback (HttpResponseBase response)
  27. {
  28. Response. Output. WriteLine ();
  29. Response. Output. WriteLine ("FALLBACK :");
  30. Foreach (var fallbackResource in FallbackResources)
  31. Response. Output. WriteLine (fallbackResource. Key + "" + fallbackResource. Value );
  32. }



Provides the configuration file service.

To provide the configuration file service, we need to add the corresponding action to the corresponding controller class to generate and return the action result of the configuration file ). In this action, we use the MVC UrlHelper object to correctly parse the route.

  1. Public ActionResult Manifest ()
  2. {
  3. Var manifestResult = new ManifestResult ("1.0 ")
  4. {
  5. CacheResources = new List ()
  6. {
  7. Url. Action ("Index", "Home "),
  8. "/Content/style.css? 6.1.3 ",
  9. "/Scripts/main. js? 6.1.3"
  10. },
  11. NetworkResources = new string [] {Url. Action ("Status", "Service ")},
  12. FallbackResources = {"/logo.png", "/logo_offline.png "}}
  13. };
  14. Return manifestResult;
  15. }



Configure routes for the configuration file

We should set a specific route for the configuration file. Most browsers do not strictly specify the location of the configuration file. The most reliable cross-browser approach is to place the configuration file in the root directory and name it cache. manifest. When the application starts, the following code adds the new "cache. manifest" route to the routing table.

  1. Routes. MapRoute ("cache. manifest", "cache. manifest", new {controller = "Resources", action = "Manifest "});



Conclusion

Offline web applications are an important part of the evolving HTML specification. Based on the actual use case, you may just use this feature to cache resources or allow web applications to run completely offline. The center of this feature is the inventory file. The configuration file format and requirements are not complex at all. Using ASP. net mvc or other server-side technologies, you can directly generate and provide the configuration file service. After compiling the configuration file, you can use the application cache API to easily cache updates. You can also use this set of APIs to query the cache status and process specific events cached by the application. To know whether the browser is onLine or offline, you can check the onLine attribute of the navigator object or handle specific onLine and offline events.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.