最近看了UC的一个页面,发现虽然也是SPA,但是首屏的加载速度极快。看了一下源码,发现它应该是把首屏的JSON数据写在页面里了,这样第一次就不必进行ajax请求。
view-source:http://qiqu.uc.cn/?uc_param_str=frpfvedncpssntnwbiprmi#!/index/index
不知道这种应该怎么实现?我用Express弄了半天楞是没弄出来。
node端的代码是这样的。
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
var context = {
title: 'My New Post',
body: 'This is my first post!'
};
res.render('index', {data: JSON.stringify(context)});
});
module.exports = router;
客户端的代码:
<!DOCTYPE html>
<html>
<head>
<META http-equiv=Content-Type content="text/html; charset=utf-8">
<title>Document</title>
<script src="http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js"></script>
<script src="http://cdn.bootcss.com/handlebars.js/4.0.5/handlebars.min.js"></script>
</head>
<body>
<p id="content"></p>
<script id="entry-template" type="text/x-handlebars-template">
<p class="entry">
<h1>{{title}}</h1>
<p class="body">
{{body}}
</p>
</p>
</script>
<script>
var json = '{{data}}'.replace(/"/g, '"');
var data = JSON.parse(json);
console.log(data); //此处可正常输出数据
var source = $("#entry-template").html();
var template = Handlebars.compile(source);
var html = template(data);
console.log(html); //此处可以打印出模板,但是数据为空
$('#content').innerHTML = html;
</script>
</body>
</html>
没太懂你想说什么,页面使用了
requireJS
做异步加载,至于写入json不就是一个JSON.stringify
嘛你可能是想这样吧(一个猜想不一定对
node
前端