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

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

tutorial:getscript_problems_in_cordova [2014/02/05 16:31] (current)
Line 1: Line 1:
 +====== 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
  
 +== ==
 +
 +<code javascript>​$.getScript("​file.js",​ function(){
 +/*
 + * CODE executed after
 + * file is fully loaded
 +*/
 +});</​code>​
 +
 +
 +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
 +
 +
 +<code javascript>​$.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;
 +}</​code>​
 +
 +Easy switching is here: just add **.fn** to your $.getScript declaration to be like so: 
 +
 +<code javascript>​$.fn.getScript("​file.js",​ function(){
 +/*
 + * CODE executed after
 + * file is fully loaded
 + *
 + * Notice fn in declaration
 +*/
 +});</​code>​
 +
 +~~DISCUSSION~~
 +
 +{{tag>​tutorial cordova phonegap jquery}}
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