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
*/
});
Enter your comment. Wiki syntax is allowed:
If you can't read the letters on the image, download this .wav file to get them read to you.
 
  • tutorial/getscript_problems_in_cordova.txt
  • Last modified: 2021/04/04 00:01
  • by Ignas