Iron Router:在模板渲染后加载js脚本

Iron Router: Load js script after template has been rendered

本文关键字:加载 js 脚本 Router Iron      更新时间:2023-09-26

Iron Router呈现模板后,我正试图加载一个javascript文件(使用IRLibloader):

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
});
Router.route('/', {
  name: 'landing',
  template: 'landing',
  onBeforeAction: function () {
    var googleAPI = IRLibLoader.load('http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false');
    var fancyInput = IRLibLoader.load('/js/fancyInput.js');
    var geoComplete;
    if(googleAPI.ready()){
      geoComplete = IRLibLoader.load('/js/jquery.geocomplete.min.js');
    }
    if(googleAPI.ready() &&
       fancyInput.ready() &&
       geoComplete.ready()){
      console.log('All ready');
      this.next(); // Render the page when all the libraries are ready
      // Testing this here
      if(Meteor.isClient){
        console.log("Meteor.isClient");
        IRLibLoader.load('/js/landing.js');
        // Set places autocomplete
        Template.landing.rendered = function(){
          $('section :input').val('').fancyInput()[0].focus();
          $('section :input').geocomplete();
          console.log("loading.js ejecutandose (after render)");
        }
      }
    }
  }
});

但当我浏览localhost:3000时,布局会被渲染,googleAPI、fancyInput和geocomplete库也会被加载,因为"all ready"消息会在控制台上打印出来,landing.js也会被下载(因为它加载了背景图像,消息"Meteor.isClient"也会被打印出来)。

但是,"着陆"模板永远不会被渲染。它的内容不会出现,并且Template.landing.rendered内部的控制台消息永远不会打印出来。这是template.js文件:

<template name="landing">
  <img id='logo' src="img/logos/logo.png">
  <div id='content'>
    <section class='input'>
      <div>
        <input type='text' placeholder='Type text here'>
      </div>
    </section>
  </div>
</template>

我还尝试用onAfterAction加载landing.js,根据Firebug控制台的说法,这似乎发生在onBeforeAction之前。真奇怪!

我不明白为什么没有加载模板,因为流星控制台上没有出现错误。知道吗?

编辑:如果我删除布局,它确实有效,看起来像这样:

<template name="layout">
  <head>
    <title>Welcome to my app</title>
  </head>
</template>

这种布局有什么问题?

所以,我认为你可能想得太多了。为什么不使用这些库的现有包?除了更容易使用之外,一些第三方代码会被缩小到主应用程序js文件中,而不是发出额外的HTTP请求来下载它们。

例如,dburles:google-maps为您提供google maps API和您选择的额外库(可以选择仅在特定路线上加载),jeremy:geocomplete为您提供geocomplete(自动将地图包作为依赖项安装)。有关实现,请参阅jeremy:geocomplete自述。

至于Fancy Input,为什么不创建一个简单的Meteor包包装器,这样你就可以只使用meteor add fancy-input了?

此外,您的Template.landing.rendered回调不应位于onBeforeAction中。理想情况下,它应该与着陆模板的其他代码一起在自己的文件中。