我可以使用yepnope/modernizer.load()检测DOM插入吗?



在windows窗体应用程序中,我们有一个Master.js文件,它在加载modernizr后被引用。

我要宣布我的现代化。在$(文档)中加载测试。在masterpage.js底部的ready函数,它迎合了基于我需要的测试加载我的js文件。

   $(document).ready(function () {
        Modernizr.addTest('mytest', $('section #myid').length > 0);    
        Modernizr.load({
            test: Modernizr.mytest,
            yep: ["custom1.js",
                "customjs2.js"],
            complete: {
                //do stuff
                }
            }
        });
    });

然而,我希望这个测试是在文件上完成的。准备就绪,并可能在之后可能出现的DOM插入点。这是可能与Modernizr或jQuery?

我的目标是在我的masterpage.js中声明所有的modernizr测试,而不是在将来可能插入需要在测试中加载资源的DOM元素后重新声明测试。

首先,Modernizr.addTest()在您的情况下并不是真正必要的(它会锁定并可能导致不希望的行为)。您可以简单地执行:

Modernizr.load({
    test: $('section #myid').length > 0,
    ...
});

不过您可以完全跳过这一步,这取决于您如何监视DOM。Livequery适用于此:

$('section #myid').livequery(function () {
    // This will run whenever a new element matches the selector: either now
    // (if the element already exists), or when it's inserted into the DOM later
    Modernizr.load({
        // no test needed - just use it as an async loader
        load: ['custom1.js', 'custom2.js'],
        complete: function () {
            // do stuff
        }
    });
    // Presumably you only want the above to run once, so remove the Livequery
    // handler now (`arguments.callee` is the current function, i.e. the event
    // handler)
    $('section #myid').expire(arguments.callee);
});

最新更新