Meteor: Wait until Library is ready

528 Views Asked by At

I've developed a package for Meteor where I'm including another JavaScript Library (Ziggeo) by appending their scripts to the HTML head.

Here's the source https://github.com/Goltfisch/meteor-ziggeo/blob/master/ziggeo.js

I sometimes get an error that ZiggeoApi is not defined if I want to call it from within my Meteor app which uses the package.

It seems that ZiggeoApi is sometimes loaded a little bit slower so that it's not immediately available to the client.

How can I wait on the client until the ZiggeoApi function is available?

I've tested stuff like

Tracker.autorun ->
  if ZiggeoApi?
    console.log 'ZiggeoApi is ready'

or put it in Template.foo.onRendered / Template.foo.onCreated

but it doesn't work.

Thanks in advance!

2

There are 2 best solutions below

0
On

Here's a dirty solution, check regularly that the API is present:

var checkForAPIInterval = Meteor.setInterval(function checkForAPI() {
  if(typeof someAPI !== 'undefined') {
    notifyAPIReady(); //Do some reactive stuff, use a plain old callback, ...
    Meteor.clearInterval(checkForAPIInterval);
  }
}, 100);
2
On

Put your library in a lib/ directory so it is loaded relatively soon in your app.

Here is Meteor's load order from the Meteor Documentation:

  1. HTML template files are always loaded before everything else
  2. Files beginning with main. are loaded last
  3. Files inside any lib/ directory are loaded next
  4. Files with deeper paths are loaded next
  5. Files are then loaded in alphabetical order of the entire path