2013-03-15 46 views
0

检测DOM插入在windows窗体应用程序中,我们有一个Master.js文件,它在加载modernizr后被引用。我可以使用yepnope/modernizer.load()

我在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

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

哦,和'$( '#身份识别码')'会稍快一些。如果您只想在'#myid'作为'

'元素的后代加载时执行该操作,那么在livequery函数中测试该条件会更具可读性。 – 2013-03-21 15:10:06

+0

欢呼斯图,这似乎是迄今为止最好的选择,尽管它看起来(看源头)基本上每20毫秒运行一次查询。因此,它不是响应dom插入事件(它看起来不存在),而是基本上检查直到选择器为真。 – Tim 2013-03-23 20:21:35

+0

你可以考虑[Mutation Observers](http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers) - 一些浏览器中的一项新功能,它可以监视DOM而无需连续查询 - 如果它们不可用,可以回到Livequery上?以下是如何检测支持:https://gist.github.com/stucox/5231211 – 2013-03-24 09:37:07