Vivek Nuna
Vivek Nuna

Reputation: 1

What is replacement of ajax call to load an html page in offline mode?

I'm navigating to an HTML page by the below code. this code works fine in the online mode (when I have internet), but it doesn't work in offline mode when there is no network connectivity.

<script>
    $(document).ready(function () {
        var homeUrl = "./js/app/views/abc.html";
        $.ajax({
            url: homeUrl, success: function (result) {
                $('#myapp').html(result);
            }
        });
    });
</script>

I thought to fix it by the below code, but I don't think its good solution, because I need to write whole HTML content as a string, so this is error-prone, complex and cannot be done easily for multiple pages. Is there any better way to do it.

<script>
    $(document).ready(function () {
        var result = "Whole html content of abc.html";
        $('#myapp').html(result);
    });
</script>

Upvotes: 1

Views: 388

Answers (1)

alexc
alexc

Reputation: 208

Have you tried storing it in localStorage? Basically, whenever you get call that endpoint, you save it's result in localStorage.

Then, when your browser is offline is your server calls returns an error, you grab the stored result from localStorage and render the page with it.

var homeUrl = "./js/app/views/abc.html";
var cacheKey = 'myUniqueCacheKey';
$.ajax({
  url: homeUrl,
  success: function (result) {
    localStorage.setItem(cacheKey, String(result));
    $('#myapp').html(result);
  },
  error: function (err) {
    var htmlString = localStorage.getItem(cacheKey);

    if (err.condition && htmlString) {
      $('#myapp').html(htmlString);
    } else {
      // do your normal error handling here
    }
  }
});

MDN: localStorage

Upvotes: 1

Related Questions