3

I want to execute JavaScript when all content (e.g. images) has been loaded in my Ember application.

I already tried using didInsertElement() and didRender() hooks, but it looks like they do not wait for background images to load.

Here's what my component's code snippet looks like:

export default Ember.Component.extend({
    didInsertElement() {
      this._super(...arguments);
      Ember.run.scheduleOnce('afterRender', this, function() {
        var home =$('#main-outlet')[0];
        home.className += " homePage";
        startTimer(5);
      });
    },
});

Any solution or an alternative approach for this?

jacefarm
  • 6,747
  • 6
  • 36
  • 46
Aman Jagga
  • 301
  • 5
  • 15

1 Answers1

2

Ember does not have an event that is equivalent to onload.

However, regarding an alternate approach, you could leverage Ember’s alias for jQuery, in combination with the didInsertElement hook within your component, to achieve the order of execution that you are looking for. Try this:

export default Ember.Component.extend({
  didInsertElement() {
    Ember.$(window).on('load', this.executeCssAnimations);
  },

  executeCssAnimations() {
    // your CSS and animation logic would go here
    Ember.$('.big-background')
         .text('NOW READY FOR CSS and ANIMATION UPDATES.')
         .css('color', 'yellow');
  },

  willDestroyElement(...args) {
    this._super(...args);
    Ember.$(window).off('load', 'window', this.executeCssAnimations);
  },
});

The willDestroyElement hook has been included as well, to show proper teardown and removal of the load event listener from window.

I’ve created an Ember Twiddle example to demonstrate this for you.

jacefarm
  • 6,747
  • 6
  • 36
  • 46
  • 1
    `didRender` gets called on every re-render, which can happen a lot of times and you probably don't want to assign a load listener every time a render happens. You only want to do it when the component is first inserted into the DOM, i.e. in `didInsertElement`. You might also want to remove it in `willDestroyElement` – nem035 Nov 03 '16 at 18:53
  • 1
    @nem035 Thanks for the good code review - updated with those refactors. – jacefarm Nov 03 '16 at 19:57