我可以包括一个文本/模板脚本从src

can I include a text/template script from a src?

本文关键字:脚本 src 包括一 文本 我可以      更新时间:2023-09-26

我试图创建一个基本的应用程序,使用骨干,下划线,和Parse。

在我的index.html中,我试着包括一些这样的脚本:

<script data-main="js/main" src="../bower_components/requirejs/require.js"></script>
<script type="text/template" id="login-template" src="js/templates/login.js">

当我尝试在我的主干部分执行以下操作时,它不工作。

template: _.template($('#login-template').html());
// ...
render: function() {
    this.$el.html(this.template());
}

然而,当我改变我的脚本,并将其直接添加到html文档中时,它工作得很好。

<script type="text/template" id="login-template">
  <header id="header"></header>
  <div class="login">
    <form class="login-form">
      <h2>Log In</h2>
      <div class="error" style="display:none"></div>
      <input type="text" id="login-username" placeholder="Username" />
      <input type="password" id="login-password" placeholder="Password" />
      <button>Log In</button>
    </form>
</script>

为什么会这样?是否有任何方法包括模板从外部来源的<script>标签?

(我不能使用$.get在这种情况下,因为它不应该使用web服务器现在和不断得到XHR错误做它正常)

为什么不工作

<script>标签的src属性将导致浏览器对login.js发出HTTP请求。但是,它不会将响应插入DOM。你需要这样做,你的代码才能工作。

浏览器不这样做的原因很简单,HTML5规范并没有说他们应该这样做。

特别地,脚本规范列出了用户代理在准备<script>标记和执行其源代码时必须采取的操作。这些列表不会指示浏览器将脚本的源代码插入DOM。内联方法之所以有效,是因为脚本源已经在DOM中了。

您可以通过检查任何带有src属性的<script>标记来看到这种行为-在加载,解析和执行其源之后,它将不包含子节点。

你能做什么

可以使用AJAX请求加载模板,但不建议这样做——如果你的应用程序有少量的模板,只把它们包含在你的主HTML文件中更简单;如果它有几个,则需要多次往返服务器来获取它们。

最好的解决方案通常是构建步骤,将模板编译成JavaScript文件中的单个对象,该对象可以像任何其他脚本一样包含在其中。

使用这样的步骤将模板编译成一个名为AppTemplates的变量,您的代码将看起来像:
template: AppTemplates['templates/login.tpl']

Grunt有一个名为Grunt -contrib-jst的任务,它为Underscore.js模板做这个工作。其他模板引擎也有类似的任务。