Javascript get status from service

I develop a web application that is getting user updates from a web service (that is in another domain) I want to get the updates every 10 seconds.

For calling the service for the first time I dynamically insert a script in the page. The service is JSONP. Then I would like to define a trigger that insert a script from 10 to 10 seconds to get the updates. Is this correct? Can I do that without affecting the user experience on the website? I mean the site performance … it will be great if I could do the call async and when I have the results I will update the status.

Is there any better solution for accessing the remote services. Is there an efficient way of dynamically reusing the same script using a trigger? I am pretty new to Javascript. Can you give me a short sample how can I define a trigger that calls a remote web service? … or if there is a better solution.

Answer

The following will dynamically create the script tags, and delete them (and the global it requires) after being finished with a given call.

You could also use CORS to allow requests besides GET ones, though as you may be aware, that is not supported in older browsers.

To avoid race conditions or performance problems during a slow network, you could allow the JSONP callback to recursively call the function, thereby only making a new call if the callback was returned, though with an optional setTimeout call to ensure there is at least a minimum delay.

The following uses Wikipedia’s API to grab a specific page revision and its user.

<script>
var JSONP = function(global){
    // (C) WebReflection Essential - Mit Style ( http://webreflection.blogspot.com/2011/02/all-you-need-for-jsonp.html )
    // 202 bytes minified + gzipped via Google Closure Compiler
    function JSONP(uri, callback) {
        function JSONPResponse() {
            try { delete global[src] } catch(e) { global[src] = null }
            documentElement.removeChild(script);
            callback.apply(this, arguments);
        }
        var
            src = prefix + id++,
            script = document.createElement("script")
        ;
        global[src] = JSONPResponse;
        documentElement.insertBefore(
            script,
            documentElement.lastChild
        ).src = uri + "=" + src;
    }
    var
        id = 0,
        prefix = "__JSONP__",
        document = global.document,
        documentElement = document.documentElement
    ;
    return JSONP;
}(this);

// Be sure to include the callback parameter at the end

function startAPI (start) {
    start = start || new Date();
    var url = 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Main%20Page&rvprop=timestamp|user|comment|content&format=json&callback';
    var minimum = 10000;
    function execute (str) {
        alert(str);
    }
    JSONP(url, function (obj) {
        for (var pageNo in obj.query.pages) {
            var page = obj.query.pages[pageNo];
            var str = 'The user ' + page.revisions[0]['user'] + ' left the page with this code ' + page.revisions[0]['*'];
            execute(str);
            var elapsed = (new Date().getTime()) - start;
            setTimeout(startAPI, (elapsed < minimum) ? (minimum - elapsed) : 0);
            break;
        }
    });
}
startAPI(); 
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *