Search code examples
javascriptember.jsember-dataember-clidiscourse

Is there any Ember event similar to `onload`


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?


Solution

  • 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.