javascript - 异步模板加载 - 如何仅加载一次?

标签 javascript ajax templates

我有一个客户端 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/

相关文章:

javascript - 将事件位置映射到非文本字段中的文本位置

javascript - 将表单名称推送到 Ajax 发送的 POST 数据中

c++ - 为什么 is_integral_v<string> 是真的?

javascript - 在变量内传递变量?

c++ - 有两个不同版本的箭头运算符?

c++ - 函数模板的显式实例化何时发生实例化

javascript - HTML5 Web Speech API 无法在本地运行

javascript - jquery 和 javascript 不工作

javascript - 所有可能的数组组合算法(匈牙利语,蛮力)

php - 验证客户端 JavaScript 事件的最佳方法