Question

I am starting to work with offline web apps. I have a little test app that makes a simple abm with localstorage when is offline, my idea is that when it is online the app uses php as backend language and to sync localstorage and php when the connection comes back.

Now, the functions used to save data to localstorage are different to those used to send data to php.

Is it possible to, dinamically, unload one JS file(lets call it offline.js) and load another(online.js)?

Or witch would be a better aproach? Should I include all the functions in one file and change the listeners dinamically?

Was it helpful?

Solution

You should have Function Wrapper with starting IF Condition checking if the browser is online.

ex:

function SaveData(data){
    if(BrowserIsOnline)
        SaveDataToPHPServer(data);
    else
        SaveDataToLocalStorage(data);

and handle each Function body differently.

OTHER TIPS

You can't unload javascript file. Once it's loaded it will always be loaded. You probably will have to rethink your design a bit.

In modern browsers you can use navigator.onLine to check for a connection. Here is the spec: http://www.w3.org/TR/offline-webapps/

var connection = navigator.onLine;

if( connection ){
    //Do AJAX
}else{
    //Do Local Storage.
}

Here is a possible solution which you may find useful...

Have a function namespace where all your logic resides, such as:

this.fn = {};
this.fn['save'] = function() {};
this.fn['load'] = function() {};

And when your events get fired, you simply use the appropriate function as in:

var fn = this.fn['load'];

or

var fn = this.fn['save'];

And then use 'fn' as you normally would.

You could even separate your functions by modules, such as 'online.js' and 'offline.js' where each module would have the same function names, but bound to it's own namespace.

When time comes to re-link the functions, you could simply do something like:

this.fn['load'] = offlineModule.fn['load'];

If you have a name for all your functions (ie: 'load', 'save') you could simply have it in a loop.

The above avoids all of the 'if/else' condition branches which can get annoying at times and instead attempts to use a kind of pattern.

But great question anyway, cause I'm starting a planning phase for a project and I will need something similar to what you describe in your question... so far, this is the best solution I have for it. Essentially inspired by the dynamic linking of SO in Linux (kind of).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top