【问题标题】:Adding a public JS in Meteor在 Meteor 中添加公共 JS
【发布时间】:2015-03-30 22:42:25
【问题描述】:

我在meteor中添加了新的公共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)

有什么想法吗?

【问题讨论】:

    标签: javascript jquery node.js meteor


    【解决方案1】:

    我通常依靠 jQuery 的 $.getScript 函数在我的 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
    };
    

    这种模式只允许在渲染给定的父模板(例如管理内容)时异步加载某些脚本,并且只在脚本加载完成时渲染相应的子模板。

    【讨论】:

    • 感谢您的回答,但仍然无法正常工作。我尝试调试并查看 Chart.min.js 是否使用 getScript 加载。我已经放置了这样的控制台日志' $.getScript("js/Chart.min.js", function () { console.log("Loaded"); template.chartLoaded.set(true); }); ' 但控制台中不显示“已加载”文本。
    • 我的错误,正确的路径应该是/js/Chart.min.js,但我忘记了答案中的前导斜杠,这个已经被编辑过,脚本需要在public/js/ 中顺便说一句。
    • 谢谢!有用。这就是流星的乏味吗? :(我来自rails。在rails中,我只是将js放入assets中,它可以工作并加载。
    • 这种模式只有在你想在你的应用程序的特定路由上加载特定的 JS 资产时才有用,如果你只是想让你的 JS 文件在启动时在每个客户端上加载,只需将你的 JS 文件放在下面的任何位置client 目录。
    猜你喜欢
    • 2017-09-26
    • 1970-01-01
    • 2016-11-26
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 2019-08-20
    相关资源
    最近更新 更多