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

时间:2013-03-15 16:42:53

标签: jquery modernizr yepnope

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

我在masterpage.js底部的$(document).ready函数中声明了我的modernizer.load测试,它适合根据我需要的测试加载我的js文件。

即。

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

但是我希望在document.ready和可能在此之后可能出现的DOM插入点上进行此测试。这可以用Modernizr或jQuery吗?

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

1 个答案:

答案 0 :(得分:1)

首先,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);
});