Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use jquery in my ios program?

Tags:

jquery

ios

iphone

I want to use jquery in my iphone program. Is it possible?

If so, anyone help me with some main steps: which files i have to import or something essential.

Thanks in advance.

like image 599
cyberworld Avatar asked Sep 13 '11 04:09

cyberworld


2 Answers

If you want to use jQuery on a remote URL within a UIWebView you can inject it using stringByEvaluatingJavaScriptFromString

Here are two methods for doing that, I opted for the second:

1. Load jQuery remotely from googleapis.com

Note: the andJS: parameter can be a vanilla JS backup in case jQuery doesn't load:

- (void)injectJQuery:(NSString *)jQuery andJS:(NSString *)js {
   // Load jQuery from googleapis.com
   NSString *jsString = @"function loadJQuery(e){try{if(typeof jQuery=='undefined'||typeof jQuery.ui=='undefined'){var t=10;var n=0;var r=document.getElementsByTagName('head')[0];var i=document.createElement('script');i.type='text/javascript';i.src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js';r.appendChild(i);checkjQueryLoaded=setInterval(function(){if(t<n){window.clearInterval(checkjQueryLoaded)}n++},300);n=0;checkLoaded=setInterval(function(){if(typeof jQuery!='undefined'){window.clearInterval(checkLoaded);e(true)}else if(t<n){window.clearInterval(checkLoaded);e(false)}n++},500)}}catch(s){e(false)}}loadJQuery(function(e){if(e){__JQUERY__}else{__JS__}})";
   jsString = [jsString stringByReplacingOccurrencesOfString:@"__JQUERY__" withString:jQuery];
   jsString = [jsString stringByReplacingOccurrencesOfString:@"__JS__" withString:js];
   [self.webView stringByEvaluatingJavaScriptFromString:jsString];
}

The only drawback to this is that it takes a second before jQuery is loaded from Google. This wasn't acceptable for my situation so I used this instead:

2. Load jQuery locally from your mainBundle (better solution I think)

Create a new file called jquery.js; paste the contents of jQuery into it; make sure it's added into Copy Bundle Resources in Build Phases; then...

- (void)injectJQuery:(NSString *)jQuery {
   NSString *path = [[NSBundle mainBundle] pathForResource:@"jquery" ofType:@"js"];
   NSString *jsString = [NSString stringWithContentsOfFile:path
                                                  encoding:NSUTF8StringEncoding
                                                     error:NULL];
   jsString = [jsString stringByAppendingString:jQuery];
   [self.webView stringByEvaluatingJavaScriptFromString:jsString];
}
like image 189
Dan Sandland Avatar answered Nov 02 '22 21:11

Dan Sandland


You can use jQuery Mobile in webviews, or a cross-platform SDK like PhoneGap which will create webviews for you.

like image 44
Matt Ball Avatar answered Nov 02 '22 19:11

Matt Ball