繁体   English   中英

使用JavaScript加载HTML模板

[英]Load HTML template with JavaScript

我正在努力为我的问题找到一个干净的解决方案,并想知道是否有人可以提供一些提示。

我有“templates.html”,其中包含一些HTML片段,我想将其加载到JavaScript中并使用。 访问模板/片段的好方法是什么,记住templates.html不是加载的DOM文档?

我正在考虑使用document.open创建一个DOM来访问,但我认为这在某些浏览器上存在问题。

使用jQuery和.load()http://api.jquery.com/load/ )方法将加载的文档注入DOM。

$(function() {
    $('#content').load('/templates.html');
});

你可以将html加载到一个隐藏的div中然后你将有一个DOM访问权限,最简单的方法是将html加载到DIV使用jquery load: http//api.jquery.com/load/

$( "#result" ).load( "ajax/test.html" );

HTMLTemplateElement ,但是现在“使用JavaScript加载HTML模板”应该引用加载HTMLTemplateElement这里是一种更现代的方法,用javascript加载本机模板,这也适用于您的用例。

首先使用<template>已经比将HTML加载到隐藏的DIV中更好,因为模板是不可见的并且不显示内容。 您可以从头开始呈现模板,并在需要时使用它们。

<html>
<head>
  <template>My template</template>
</head>
<body>
  <script>
  document.body.append(
    document.importNode(
      document.querySelector('template').content,
      true
    )
  )
  </script>
</body>
</html>

或者动态创建它们。

const template = document.createElement('template')
// modify the template's content
template.content.append(document.createElement('div'))
// add it to the document so it is parsed and ready to be used
document.head.append(template)

因为我们希望基于我们从网络获得的某些文本来构建模板的内容,所以我们必须解析它并将其添加到我们的template.content

const text = fetchTemplateSomehowAsText('my-template.html')
const parsedDocument = new DOMParser().parseFromString(text, 'text/html')
template.content.append(parsedDocument.querySelector('#my-snippet'))

如果my-template.html已经包含在<template>标记中,我们可以避免手动创建模板元素,因为DOMParser已经为我们创建了模板元素。

document.head.append(
  new DOMParser().parseFromString(text, 'text/html')
    .querySelector('template')
  )
)

是我用来将模板动态加载到文档中的片段,使用我刚才解释的内容。

另一种方法是使用requireJS

require (['text!template_name'], function(yourTemplate) {
  // do stuff in here with yourTemplate dinamically load
}

对于简单的要求,您可以尝试:

var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {     
        //do something with xhr.responseText
    }   
};      
xhr.open('GET', '/template.html');
xhr.send();  

你可以使用jquery ajax加载模板异步

$.get("/html/template01.html")
.done((data) => {
    console.info(data); // output the content of the html file
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM