Search code examples
javascriptjquerybackbone.jsunderscore.jsunderscore.js-templating

Waiting for images to load in underscore template


I'm loading images inside underscore. I have a class in my container which has a loader image and it will disappear once my images are loaded.

<div id="main_container" class="loading">
<% for (i = 0; i <= pages; i++) { %>
      <img src="/image_<%=i%>.jpg" id="image_<%=i%>" />
      <%
          $('#image_'+i).load(function() {
              $('#main_container').removeClass('loading');
          }).each(function() {
            if(this.complete) $(this).load();
          });
      %>
<% } %>
</div>

I can't make it work maybe because the dom is not yet created. Is there a way for me to load the images in underscore template and remove the class loading when the images is completely loaded?

Thanks and more power


Solution

  • Just render your template with the class loading on your image and add the callback onload

    <% for (i = 0; i <= pages; i++) { %>
        <img src="/image_<%=i%>.jpg" class='loading' onload='hideLoading(this)' />
    <% } %>
    

    In your scripts file, add the callback

    function hideLoading(img) {
        $(img).removeClass('loading');
    }