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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With