0

I'm developing a phonegap app that shows a random background image on each page.

Basically it does (coffeescript)

img = Math.floor Math.random() * 16
elem.css 'background-image', "url(img/backgrounds/#{img}.jpg)"

every time the page changes

The problem is that it removes the old image before the new image is loaded, letting the page without background meanwhile.

How can I fix that?

(I've already tried to preload the images)

Dawson Loudon
  • 6,029
  • 2
  • 27
  • 31
Pedro Bernardes
  • 706
  • 1
  • 8
  • 20

1 Answers1

0

Thanks to this link How can I check if a background image is loaded?, thanks to @Joel Brewer I've managed to find a solution

Using the plain solution given on answer solved the problem of the temporary lack os background image, but the delay was still there and very annoying.

And I think since it is a phone, it will not allow me to precache a bunch of big images (And even if it is not the case, I shouldn't do that)

So, basically, what I did was to precache only the next image, the solution, in coffeescript, follows:

# The class
class ImageLoader
  constructor: (@src_gen) ->
    @precache_obj = $ '<img style="position: absolute; top: -9999px"/>'
    $('body').append @precache_obj
    @precache()

  precache: ->
    @precache_src = @src_gen()
    @precache_obj.attr 'src', @precache_src

  get_image_src: ->
    src = @precache_src
    @precache()
    src


# The initialization
Layouts.background_loader = new ImageLoader ->
  img_n = Math.floor Math.random() * 16
  "img/backgrounds/#{img_n}.jpg"

# The call
random_background: (elem) ->
  elem.css 'background-image', "url(#{Layouts.background_loader.get_image_src()})"
Community
  • 1
  • 1
Pedro Bernardes
  • 706
  • 1
  • 8
  • 20