Dennis
Dennis

Reputation: 441

Adapting a coffeescript to use window.onload

I have the following coffeescript, which works except for the fact that when images take a while to load it runs before the images are loaded and then doesn't have the desired effect:

ready = ->
  jQuery ->
    $('.box').find('img').each ->
      imgClass = if @width / @height > 1 then 'wide' else 'tall'
      $(this).addClass imgClass
      return
    return


$(document).ready(ready)
$(document).on('page:load', ready)

How can I run my function only after the entire window is loaded?

My best attempt so far looks like

window.onload = ->
  $('.box').find('img').each ->
    imgClass = if @width / @height > 1 then 'wide' else 'tall'
    $(this).addClass imgClass
    return
  return

but it doesn't work. I've tried several other possibilities too but I can't figure out whats wrong.

My question is different from this one since I don't want to wait until all the coffeescripts have finished loading, I want to wait until all of the images in my webpage have loaded.

Upvotes: 8

Views: 7231

Answers (1)

Wes Foster
Wes Foster

Reputation: 8900

To execute your desired code AFTER all images are loaded, use jQuery's load() method on the window. document watches the DOM, while window watches the contents.

In coffee, it would look like this:

$(window).load ->
  alert 'All images are loaded'

The difference between this and what you had is you were using window.onload whereas I'm suggesting $(window).load().

Upvotes: 7

Related Questions