Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

javascript - Meteor JS: use external script

There are some services (like FB like or AddThis) that provide a snippet of code. It looks like

<div class="service-name" data-something="x"></div>
<script type="text/javascript" src="http://service-domain.com/service-name.js"></script>

OK, cool, so normally you paste it to your HTML and it works. Not with Meteor.

Here's what I see:

  • <script> inside of template / body is not loading -- I don't see it in Resources, something in Meteor is actually preventing browser from recognizing it as a JS file
  • it works from <head>

Now here are the problems and questions:

  1. I don't want loading it from <head> -- because of the speed
  2. Even if I load it from there -- we have QA and PROD environments. They must load this script from different domains (like service-domain-qa.com vs. service-domain.com)

And surprisingly you cannot use template helpers / variables in the <head>.

With traditional frameworks it's not a question at all - you can include scripts anywhere and they just load; you can use logic / variables in any part of you server templates.

So, how should I do this in Meteor? Let me repeat:

  • I need some external scripts (hosted on 3rd party domain) to be loaded into my app page
  • Saving this script into my project's folder is not an option
  • Script path depends on the environment (we already have the settings system), so the place of the template that renders it should be passed some data from the code

I know the way to achieve this with dynamic script loading from my code (with LAB.js or whatever) on Template.created, but this is so much an overkill...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

<script> tags in body or templates aren't executed by Meteor, they are parsed and then handled by Meteor's templating system. You can't expect a script tag in either of those to just work as it would with a normal HTML page.

The solution is to use Template events (where you could manually append the script tag to the body or something) or load it dynamically like you said. It's not overkill, it's how Meteor works - remember, there is no traditional HTML page or body, there's just the Meteor API, and the Meteor API specifies that in order to load and execute external scripts, you must use the appropriate API methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...