Tags:
create new tag
view all tags

JStorage Contrib Package

Store/cache data locally in the browser using JavaScript

Introduction

jStorage is a cross-browser key-value store database to store data locally in the browser - jStorage supports all major browsers, both in desktop (yes - even Internet Explorer 6) and in mobile. This JStorageContrib package packages the jstorage.js JavaScript library and a dependent json2.js library.

jStorage home: http://www.jstorage.info/

Documentation

The usage is best described with a use case:

Use case: You want to periodically refresh content in a sidebar or a header via an Ajax call, such as once every minute. If the Ajax call is slow it takes a toll on every page load when browsing the site.

Solution: Store the result of the Ajax call locally in the browser. Use the locally stored data if it is fresh enough, else do another Ajax call to refresh it. This should work across pages when browsing the TWiki site.

Example

The following example is somewhat silly, but it serves as an example to study and understand how the local storage works. The example shows a box with the current GMT time. The time is stored locally in the browser. If this page is reloaded within a minute, the locally stored time is shown. If over a minute, or if you let the page sit for over a minute, two Ajax calls are made. The first one sets the current GMT time in a SetGetPlugin variable on the server, the second call reads it back from the server; on success the time is stored locally in the browser, so that a page reload can get the time without an Ajax call.

Working example - box with current GMT time:

Underlying HTML and JavaScript:

<div id="exampleID" style="border: solid gray 1px;">
</div>

%INCLUDE{%SYSTEMWEB%.JStorageContrib}%
<script type='text/javascript'>
function refreshExampleData(id) {
    var exampleData = $.jStorage.get(id);
    if(exampleData){
        updateExampleData(exampleData);
    } else {
        var loading = '%ICON{processing-bg}% refreshing...';
        $('#exampleID').html(loading);
        var now = new Date().toJSON().slice(11, 19);
        var exData = 'Example time: ' + now + ' GMT';
        var ajaxPostUrl = '%SCRIPTURL{rest}%/SetGetPlugin/set';
        var ajaxGetUrl = '%SCRIPTURL{rest}%/SetGetPlugin/get';
        $.ajax({
            type: "POST",
            url: ajaxPostUrl,
            data: { 'name': id, 'value': exData, 'remember': 1 },
            success: function(data) {
                $.ajax({
                    type: "GET",
                    url: ajaxGetUrl,
                    data: { 'name': id },
                    success: function(result) {
                        $.jStorage.set(id, result);
                        // set 60 sec TTL (time to live)
                        $.jStorage.setTTL(id, 60000);
                        updateExampleData(result);
                    }
                });
            }
        });
    }
}

function updateExampleData(exampleData) {
    $('#exampleID').html(exampleData);
}

$(document).ready(function() {
    refreshExampleData('exampleVar');
    var refreshId = setInterval(function() {
        refreshExampleData('exampleVar');
    }, 10000); // 10 sec refresh time
});
</script>
Explanation:

The div tag with id "exampleID" is empty - its content is set dynamically via JavaScript code.

The %INCLUDE{%SYSTEMWEB%.JStorageContrib}% includes the necessary JavaScript libraries for browser local storage.

The jQuery ready() function at the bottom does two things:

  • Refresh the example data by calling refreshExampleData().
  • Set up a timer that refreshes the example data once every 10 seconds.

The refreshExampleData function first gets the local storage by ID: $.jStorage.get(id). If the data exists and is not too old, the "exampleID" div is updated - this is fast because the data is retrieved from a local browser storage.

If not, two nested Ajax calls are made. The first one sets a SetGetPlugin variable with the current GMT time. On success, a second Ajax call is done to read the same SetGetPlugin variable. The following actions are done on success of the second call:

  • $.jStorage.set(id, result); - store the result in the browser for later use.
  • $.jStorage.setTTL(id, 60000); - set 60 sec TTL (time to live).
  • updateExampleData(result); - update the "exampleID" div.

In a real use you likely just have one Ajax call to read the data, not two calls.

Using this setup, the user sees the example data without delay, except when the data is too old; in which case it is refreshed with an Ajax call to the server.

Section for Include

This section defines the JavaScript include. To use JStorage in JavaScript code you first need to include the library:

%INCLUDE{%SYSTEMWEB%.JStorageContrib}%

Installation Instructions

You do not need to install anything on the browser to use this extension. These instructions are for the administrator who installs the package on the server where TWiki is running.

  • For an automated installation, run the configure script and follow "Find More Extensions" in the in the Extensions section.

  • Or, follow these manual installation steps:
    • Download the ZIP file from the package home (see below).
    • Unzip JStorageContrib.zip in your twiki installation directory. Content:
      File: Description:
      data/TWiki/JStorageContrib.txt Contrib documentation topic
      pub/TWiki/JStorageContrib/*.js JavaScript files
      lib/TWiki/Contrib/JStorageContrib.pm Contrib Perl module
    • Set the ownership of the extracted directories and files to the webserver user.

Contrib Info

  • One line description, is shown in the TextFormattingRules topic:
    • Set SHORTDESCRIPTION = Store/cache data locally in the browser using JavaScript

Author: TWiki:Main.PeterThoeny
Copyright: © 2015 Canadian National Railway
© 2015 TWiki:Main.PeterThoeny
© 2015 TWiki:TWiki.TWikiContributor
json2.js: © 2011-2015 http://www.JSON.org/js.html
jstorage.js: © 2010-2014 Andris Reinman, andris.reinman[at]gmail.com, http://www.jstorage.info
License: GPL ( GNU General Public License)
Sponsor: Canadian National Railway
Version: 2015-11-06
2015-11-06: TWikibug:Item7696: Example only works for authenticated user, so adding note to login first
2015-11-02: TWikibug:Item7696: Initial version
TWiki Dependency: $TWiki::Plugins::VERSION 6.0
CPAN Dependencies: none
Other Dependencies: none
Perl Version: 5.005
Plugin Benchmark: GoodStyle nn%, FormattedSearch nn%, JStorageContrib nn%
Home: http://TWiki.org/cgi-bin/view/Plugins/JStorageContrib
Feedback: http://TWiki.org/cgi-bin/view/Plugins/JStorageContribDev
Appraisal: http://TWiki.org/cgi-bin/view/Plugins/JStorageContribAppraisal

Related Topics: TWikiContribs, TWikiPreferences

Topic attachments
I Attachment History Action Size Date Who Comment
Unknown file formatmd5 JStorageContrib.md5 r3 r2 r1 manage 0.2 K 2015-11-06 - 22:53 PeterThoeny  
Compressed Zip archivetgz JStorageContrib.tgz r3 r2 r1 manage 21.5 K 2015-11-06 - 22:53 PeterThoeny  
Compressed Zip archivezip JStorageContrib.zip r3 r2 r1 manage 25.3 K 2015-11-06 - 22:53 PeterThoeny  
Unknown file formatext JStorageContrib_installer r1 manage 3.6 K 2015-11-06 - 22:53 PeterThoeny  
Edit | Attach | Watch | Print version | History: r3 < r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r3 - 2018-07-17 - PeterThoeny
 
  • Learn about TWiki  
  • Download TWiki
This site is powered by the TWiki collaboration platform Powered by Perl Hosted by OICcam.com Ideas, requests, problems regarding TWiki? Send feedback. Ask community in the support forum.
Copyright © 1999-2024 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.