Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js include external script on specific page

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.

like image 477
Jared Avatar asked Feb 09 '15 14:02

Jared


1 Answers

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.

like image 103
Duncan Walker Avatar answered Oct 20 '22 22:10

Duncan Walker