在Meteor中添加一个公共的JS
我已经在meteor中join了新的公共javascript,并且加载了这个
if (Meteor.isClient) { Template.hello.created = function() { $('head').append('<script type="text/javascript" src="/js/Chart.min.js">'); }; }
但是我在浏览器控制台中得到了这个错误
Uncaught SyntaxError: Unexpected token < jquery.js?dd8bac56f8fd3666d433d2285ae01e52597cc51a:372 (anonymous function)
有任何想法吗?
我通常依靠jQuery的$.getScript
函数来asynchronous加载我的Meteor应用程序中的其他JS文件,使用ReactiveVar
(不要忘记meteor add reactive-var
)来跟踪脚本的可用性:
HTML
<template name="parent"> {{#if chartLoaded}} {{> child}} {{/if}} </template> <template name="child"}} {{! here we can assume the script is loaded}} </template>
JS
Template.parent.created = function() { this.chartLoaded=new ReactiveVar(false); var template=this; $.getScript("/js/Chart.min.js",function(){ template.chartLoaded.set(true); }); }; Template.parent.helpers({ chartLoaded:function(){ return Template.instance().chartLoaded.get(); } }); Template.child.rendered=function(){ // safely use Chart.min.js functionality };
这种模式只允许在给定的父模板被渲染的时候(比如pipe理员的东西)asynchronous加载某些脚本,并且在脚本完成加载时只处理相应的子模板。