Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preload images with PhoneGap?

I've come to believe that there's two things happening. Firstly, if you want to preload a url, you can do this:

body:after{
   content: url(http://www.example.com/img/img_1.png) display:none;
}

But as far as I know, this doesn't help in this case:

body:after{
   content: url(../img/img_1.png) display:none;
}

In this latter case, the image is already local, so it doesn't have to "download" it? Is that true? Or will the first bit of code cache the image even more?

I ask, because even though I do this, and I then transition to another page, using jquery mobile, the next page still takes a few seconds to load the background image. Even though it's a local asset.

How do I get around this?

like image 879
coderama Avatar asked Aug 14 '15 07:08

coderama


2 Answers

From the tests I've done, it seems that two things can cause a delay when loading an image:

  1. When the image needs to be loaded from a URL, or
  2. When the image is locally located, but needs to be placed on the display screen

What i didn't realise is that with PhoneGap, even with the images local, it might take a little while to load. This is what was causing issues for me. Well, this and the fact that I was loading from URLs. So in my case I used the "CSS3 Caching Plugin" like so:

jQuery(function($) { 
    $.preload.images(document) 
});

This solved my problem of loading images that was in the CSS file. But then for my own convenience, I added a section to the css file for locally cached files. Like so:

#cacheMe1 { background: #ffffff url('../img/img1.png') 50% 50% repeat-x; }
#cacheMe2 { background: #ffffff url('../img/img2.png') 50% 50% repeat-x; }
#cacheMe3 { background: #ffffff url('../img/img3.png') 50% 50% repeat-x; }
#cacheMe4 { background: #ffffff url('../img/img4.png') 50% 50% repeat-x; }
etc

This solved caching for most images, plus it allowed me to still keep URLs as loading in the app (i have a gallery section where its currently acceptable to see the images load, rather than on display).

What I also did that seems to be working, is that I use the "InAppBrowser" plugin to preload entire pages by opening them in a hidden window:

var ref = window.open('http://www.example.com', '_blank', 'hidden=yes');

If you open a bunch of files on load of the app, it seems when you either open these URLs again, or switch to the window with:

ref.show();

So there's two decent ways I've found to cache files that works perfectly for my scenario. Hope it helps someone else!

like image 146
coderama Avatar answered Sep 22 '22 17:09

coderama


I do not know if I understood well, but maybe it can useful for you:

<img src="my.png" onerror="this.src = 'image-not-found.png';" />
like image 20
candlejack Avatar answered Sep 23 '22 17:09

candlejack