Javascript XMLHttpRequest慢…如何更快地完成同样的事情?
这是我用来从文件中加载我的把手模板的函数。我发现它非常慢,即使我加载本地文件。在我看来,XMLHttpRequest对于本地文件来说并不是很大。有没有一种方法可以用jQuery get或其他更快的方法做同样的事情?谢谢Javascript XMLHttpRequest慢…如何更快地完成同样的事情?,javascript,jquery,xmlhttprequest,handlebars.js,Javascript,Jquery,Xmlhttprequest,Handlebars.js,这是我用来从文件中加载我的把手模板的函数。我发现它非常慢,即使我加载本地文件。在我看来,XMLHttpRequest对于本地文件来说并不是很大。有没有一种方法可以用jQuery get或其他更快的方法做同样的事情?谢谢 function getTemplate (name, callback, dir) { if (dir === undefined) dir = '' var xhr = new XMLHttpRequest() var url = '/scripts/templa
function getTemplate (name, callback, dir) {
if (dir === undefined) dir = ''
var xhr = new XMLHttpRequest()
var url = '/scripts/templates/' + dir + name + '.html'
xhr.open('GET', url, true)
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var raw = xhr.responseText
var compiled = Handlebars.compile(raw)
callback(compiled)
}
}
xhr.send()
}
用法示例:
getTemplate('no-results', function (tmp) {
$(historyContainer).append(tmp())
})
阅读关于Fetch的文章。您可以使用Fetch而不是XMLHttpRequest
Example:
@meth = GET | POST | PUT
@url = path
@data = {test1: "teste1"}
function ajaxRequest(meth, url, data) {
return fetch(url, {
method: meth,
headers: {'Content-Type': 'application/json'},
body: data,
credentials: 'same-origin'
})
.then(resp => {
if(resp.status != 200) throw new Error(resp.statusText)
return resp.text()
})
}好的,这个调整接缝的方法很好
function getTemplate (name, callback, dir) {
if (dir === undefined) dir = ''
var xhr = new XMLHttpRequest()
var url = '/scripts/templates/' + dir + name + '.html'
return fetch(url).then(function (res) {
return res.text()
}).then(function (html) {
var compiled = Handlebars.compile(html)
callback(compiled)
})
}
你能做一个计时器,看看是渲染还是请求占用了最多的时间吗?你介意根据我的示例显示fetch用法吗?