我有一个客户端 JS 应用程序,需要加载模板来显示每个项目。假设它们是笔记。
问题出在异步部分。我无法使模板仅加载一次。每次注释调用 render
函数时都会加载它。
这是一些代码:
var notes = [ {}, {}, {} ] // Some Note objects
notes.forEach( function( note ) {
render( note )
}
// Have some variable to hold the template
var template
// Now on the render function
function render( note ) {
// First, if the template exists, go straight to the next function
if ( template ) {
// The display function takes care of appending the note
// to the body after applying datas on the template
display( note )
}
else {
// loadTemplate just loads the template in an ajax request
// and executes the callback with the template as argument
loadTemplate( function( data ) {
// I fill in the template variable
template = data
// And I display the note since the template is available
display( note )
} )
}
}
因此,在这种情况下,即使有检查来防止这种情况,它也会加载模板的三倍。我猜这是因为这三个模板直接进入了 else,但我怎样才能防止这种情况发生呢?
我不想使用同步 ajax 加载,因为这会卡住浏览器。
编辑:最后,我使用了@Managu的解决方案,稍作修改。
我没有使用他的循环,而是使用了以下更优雅的循环:
while ( backlog.length ) {
display( backlog.shift() )
}
最佳答案
var loadTemplate = function() {
var promise = $.get( "/" );
loadTemplate = function() {
return promise;
};
return promise;
};
请注意,这里不需要 jQuery,我只是编写伪代码。您可以使用任何提供延迟的库。
loadTemplate().then( function( data ) {
// I fill in the template variable
template = data
// And I display the note since the template is available
display( note )
} )
关于javascript - 异步模板加载 - 如何仅加载一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10358750/