Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to add external javascript code?

Tags:

ember-cli

I would like to add some jQuery code on my page which needs to be loaded after the page is rendered?

What is the best way to include in ember-cli?

Do we need to create a new custom js file and use app.import to import that js file?

Thanks a lot.

like image 718
TheOneTeam Avatar asked Dec 15 '14 06:12

TheOneTeam


1 Answers

Recommended

You would generally want to do it within an Ember.View or Ember.Component. Both of these implement a didInsertElement hook that you can use to access the DOM elements after they have been rendered.

Here's an example:

export default Ember.View.extend({
  didInsertElement: function() {
    // this.$() is a scoped selector to the current view
    this.$().yourJqueryFunction(); 
  }
}

This is the recommended practice as you can guarantee that the DOM is present at that time. If you just slap on a jQuery function after the app js is loaded, it's very possible it's not present on the screen yet so it wouldn't be called. It's also possible that you are not on the route where this jQuery code is used and then you navigate to it. At this point it wouldn't be triggered properly

ember docs found here

Other way

You could drop your js file in the vendor/ folder and use the app.import API to import it into the vendor.js file at build time. The main disadvantage of this is you don't have direct access to your ember app or ES6 modules or other things your addon's may add.

like image 151
jakecraige Avatar answered Nov 12 '22 20:11

jakecraige