8

I'm trying to figure out how to include an external javascript source (Exhibit), but only for a single page on the site. Can it be done in the view or template?

I found that simply adding <script src="exhibit.js"></script> to the page template doesn't work. If I add it to the template for the entire site it loads just fine, however it loads on every page.

The other side of my problem may be more specific to exhibit. Is there a way to have the script sourced every time the page is loaded? Example: When I first visit the page that contains the exhibit script, it loads the ember app including exhibit and the page is displayed properly. I navigate away from the page, when I return to the page the exhibit script is not reloaded, thus not redrawing the page properly as it did the first time it was visited.

1
  • Are you building your application using components? Commented Feb 9, 2015 at 16:24

1 Answer 1

16

If you're building your app with Ember CLI and exhibit.js is a fairly small file you might be better off including exhibit.js in your vendor.js file to mininize HTTP requests.

However, if you want to load exhibit.js in a single route your could use the polyfill method described in this answer like so:

// app/controllers/some-route-name.js    

import Ember from 'ember';

export default Ember.Controller.extend({

  loadPlugin: function() {
    // Use run loop if you need to setup the DOM first
    Ember.run.scheduleOnce('afterRender', this, function() {
      Ember.$.getScript('path/to/exhibit.js');
    });
  }.on('init')

});

This will asynchronously load the file. The getScript docs are here - you'll see you can use callbacks too.

If you don't need the DOM setup before loading, you can remove the run loop. Loading this script on the controller's init event will prevent it from reloading everytime the user navigates to the route. If you do want to load the script everytime you could move getScript to the view's didInsertElement event.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I put getScript in didInsertElement and it works perfectly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.