You are here: Hello » Tutorials » JQuery getScript not working in Cordova

JQuery getScript not working in Cordova

Creating Cordova (formerly known as PhoneGap ) application aimed to work with 1.6+ Android I've faced strange problem. Android 4.0.* versions devices does not load script via jQuery command getScript. And this was only in 4.0.* version devices

$.getScript("file.js", function(){
/*
 * CODE executed after
 * file is fully loaded
*/
});

This would not be a problem, if all logic would be in one file. But this greatly hardens development and maintenance. I have solved it by using adequate function, that loads JS file. Here is code (I presume you are already declared jQuery). Add this to document.ready declaration

$.fn.getScript = function(src, callback) {
    var s = document.createElement('script');
    document.getElementsByTagName('head')[0].appendChild(s);
    s.onload = function() {
        //callback if existent.
        if (typeof callback == "function") callback();
        callback = null;
    }
    s.onreadystatechange = function() {
        if (s.readyState == 4 || s.readyState == "complete") {
            if (typeof callback == "function") callback();
            callback = null; // Wipe callback, to prevent multiple calls.
        }
    }
    s.src = src;
}

Easy switching is here: just add .fn to your $.getScript declaration to be like so:

$.fn.getScript("file.js", function(){
/*
 * CODE executed after
 * file is fully loaded
 *
 * Notice fn in declaration
*/
});

Discussion

Enter your comment:
N Q᠎ X W K
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported

Hey.lt - Nemokamas lankytojų skaitliukas XHTML