2017-04-15 28 views
0

这是我用来从文件中加载我的Handlebars模板的函数。即使我正在加载本地文件,我发现它很慢。在我看来,XMLHttpRequest()对于本地文件来说并不是很大。有没有办法与例如做同样的事情。 jQuery的get()或更快?由于使用的XMLHttpRequest慢...如何更快地做同样的事情?

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()) 
    }) 
+0

你可以做一个计时器,看看它的渲染,或者某个花费大部分时间的请求? – nixkuroi

回答

0

好这个调整接缝处做工精良

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) 
    }) 
} 
-1

阅读this文章关于获取。您可以使用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() 
    }) 

}

+0

你会介意根据我的示例显示提取使用情况吗? – Spyder

相关问题