davidd8 / meteor-external-file-loader

The external file loader package makes it easy to load external js and css files dynamically within Meteor.
MIT License
69 stars 7 forks source link

meteor-external-file-loader Build Status

The external file loader package makes it easy to load external js and css files dynamically within Meteor.

Whereas non-Meteor web applications can simply add a <script> tag to their html header template, Meteor cannot. Adding third-party javascript code to meteor apps is a bit cumbersome. The fact that the <head> portion of meteor templates is not your normal html <head> for a web page further complicates the matter.

This package aims to make it easier.

Installation

$ mrt add external-file-loader

Dependencies: meteorite, jquery meteor smart package

Usage

  1. Pick a third-party js library to add to your application.
  2. Load the library in the template that you'll use it in.
  3. Use the library once it's been loaded.

Script Example

Using stripe.js as the example. We'll load it into the billing template, and charge people money.

var chargeRandomPerson = function() {
  // Do something here with the stripe api.
};

Template.billing.created = function() {
  Meteor.Loader.loadJs("//js.stripe.com/v2/", chargeRandomPerson);
};

The method returns a jQuery promise, for easy error handling in case the script cannot be loaded.

The request times out after a while in case the script cannot be found. The default is 5000ms, but is customizable:

// These 2 calls are equivalent, and set a 10s timeout
Meteor.Loader.loadJs("//www.google.com/jsapi", sucessCallback, 10000).fail(retryMessageCallback)
Meteor.Loader.loadJs("//www.google.com/jsapi", 10000).fail(retryMessageCallback).done(successCallback);

HTML Examples

Our example plain HTML fragment fragment.html, assumed to be served in these examples as static content under public.

<div>I'm text, with a <button>button</button>.</div>

Here's loading our external HTML fragment via a Handlebars helper.

Handlebars.registerHelper('loadHtml', function() {
    var template = Meteor.Loader.loadHtml('/fragment.html','new_template_name');

    // here we're passing the current data context of the parent template to our fragment
    return template(this);
});

Here's loading the same fragment and inserting into the DOM manually.

Meteor.startup(function() { // dom is ready
    var fragment = Meteor.render(function() {
        var tpl = Meteor.Loader.loadHtml('/fragment.html','new_template_name');

        // catch an event this time
        tpl.events({
            'click button': function() {
                console.log('hello!');
            }
        });

        return tpl();
    });

    $('#inserthere').html(fragment);
});

Methods

Contributing

To run the tests:

$ mrt test-packages external-file-loader