3

jQuery を使用して多数の小さな .html ファイルをロードしようとしています。コードの特定の部分を実行する前に、それらをすべて DOM に配置します。しかし、これは非常に困難であることが証明されています。1つのファイルを十分に処理できるようにすることはできますが、複数のファイルを処理しようとしても機能せず、その理由を理解できません。

これは、1つのファイルを実行できるコードです。

var templates = (function ($, host) {
    // begin to load external templates from a given path and inject them into the DOM
    return {
        // use jQuery $.get to load the templates asynchronously
        load: function (url, target, event) {
            var loader = $.get(url)
                .success(function (data) {
                    // on success, add the template to the targeted DOM element
                    $(target).append(data);
                })
                .error(function (data) {

                })
                .complete(function () {
                    $(host).trigger(event, [url]);
                });
        }
    };
})(jQuery, document);

これは次のように使用されます。

templates.load("file1.html",
    "#templates-container", "file1-loaded");


$(document).on("file1-loaded", function (e) {
    // execute the rest of the page
});

ただし、複数のファイルをロードする必要がある場合、これはフラットになります。だから私はこれを試しました...

(function ($, host) {
    $.fn.templates = function (options) {
        var settings = $.extend({
            queue: [],
            element: this,
            onLoaded: function () { }
        }, options);

        this.add = function (url) {
            settings.queue.push(url);
            return settings.element;
        }

        this.load = function () {
            $.each(settings.queue, function (index, value) {
                $.get(value).success(function (data) {
                    $(settings.element).append(data);
                });
            });

            settings.onLoaded.call();
        }

        return settings.element;
    }
})(jQuery, document);

このように動作することを目的としています...

$('#templates-container').templates({
    onLoaded: function () {
        // execute the rest of the code
    }
}).add('file1.html').add('file2.html').done();

しかし、それは完全に失敗するだけであり、その理由については何の兆候もありません。エラーメッセージすら表示されません。しかし、onLoaded が適切に呼び出されることはありません。

4

1 に答える 1