2

I'm trying to load an external script while using Meteor.

Currently using this code in my layout.js to some success.

Meteor.startup( function() {
    $.getScript('js/scripts.js');
});

However, if I go to another url and come back to it, the script no longer works. (I see it not working because my background cover image disappears.)

Michael M.
  • 10,486
  • 9
  • 18
  • 34
eddiewang
  • 415
  • 5
  • 21

2 Answers2

4

Any external scripts should be placed in client/compatibility, and Meteor will load it for you; no need for $.getScript('js/scripts.js');

You can then instantiate that script on the template like:

Template.game.onRendered(function(){
  $('.grid').isotope({});
});
Radu Chiriac
  • 1,374
  • 3
  • 18
  • 34
  • that does not work for certain scripts that need to be loaded at the end of the body, after assets have been loaded. (e.g. scripts.js and parallax.js) – eddiewang Aug 15 '15 at 15:07
  • Sure it does. Just make sure you always load that script when the Template is ready. In Meteor world you do `Template.game.onRendered(function(){});` (like you discovered your self). I don't see where it would look for `/js/scripts.js`. I the `public` directory I hope. But that's bad practice for so many reasons. – Radu Chiriac Aug 15 '15 at 15:52
  • You're right. I can see why it would be bad practice. I've updated my code to use yours! Additionally, for some reason onRendered only works 50% of the time. I think the Isotope methods are messing up (onRendered doesn't account for images to load, so scripts.js executes the masonry/lightbox functions before images are loaded). Do you know a. if that's the issue and how can I solve it, or b. i'm totally wrong and it's another issue alltogether. – eddiewang Aug 15 '15 at 15:59
  • I think it's more of a Isotope issue and not Meteor. It has to deal with images not being cached. Take a look at this [example](http://imagesloaded.desandro.com/) and fire up Isotope only when all images are loaded: [http://stackoverflow.com/questions/23387010/isotope-not-working-with-imagesloaded](http://stackoverflow.com/questions/23387010/isotope-not-working-with-imagesloaded) – Radu Chiriac Aug 15 '15 at 16:19
  • I'll look into it now. It worked when it was just in pure html/css/js form. The isotope uses the "layoutComplete" `msnry.on('layoutComplete', function() { ... });` Does that change things? – eddiewang Aug 15 '15 at 16:22
  • Sorry, I'm not really familiar with the events in Isotope – Radu Chiriac Aug 15 '15 at 16:27
  • Well, this certainly solves my nightmare $.getScript nesting +1 – danwild Jan 14 '16 at 05:02
1

For anyone needing help with this, replace Meteor.startup with Template.name.onRendered. This helped solve my issue. Cheers!

eddiewang
  • 415
  • 5
  • 21