How to include JavaScript from a CDN in meteor?

后端 未结 3 1050
孤城傲影
孤城傲影 2021-02-05 06:04

I\'d like to include JS from a CDN in Meteor before including my own client scripts so that the client scripts can depend on it.

...


        
相关标签:
3条回答
  • 2021-02-05 06:17

    You can append the script after the template is rendered. So your script will load only after every other line has been loaded. For example if you directly add a jquery plugin to your template html file, you'll get "jquery not found" error. But this approach prevents that:

    Template.Main.onRendered(function () {
    
          $('head').append('<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-formhelpers/2.3.0/js/bootstrap-formhelpers.js"></script>');
    
    });
    
    0 讨论(0)
  • 2021-02-05 06:20

    There's also an abandoned package called meteor-external-fileloader that gives an example using Stripe.js. It hasn't been maintained since September 2013, so be careful.

    0 讨论(0)
  • 2021-02-05 06:28

    Assuming you don't need to load these files before the Meteor packages, create a JS file which is loaded before any of the others. Meteor loads files in alphabetical order so it must be the first file loaded. To that end, naming it aaLoadCDN.js should suffice. Dynamically load the CDN scripts by adding a script src element to the document head:

    var script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');  // optional
    script.setAttribute('src', 'url/to/the/cdn/script.js');
    document.getElementsByTagName('head')[0].appendChild(script);
    

    Here are some real-world Meteor packages loading scripts from CDNs:

    • snapsvg
    • Font-Awesome (CSS).
    0 讨论(0)
提交回复
热议问题