2013-03-15 3 views
0

Windows 양식 응용 프로그램에는 modernizr을로드 한 후 참조되는 Master.js 파일이 있습니다.yepnope/modernizer.load()를 사용하여 DOM 삽입을 감지 할 수 있습니까?

내 modernizer.load 테스트는 masterpage.js의 하단에있는 $ (document) .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 
       } 
      } 
     }); 
    }); 

은 document.ready에 잠재적이 후 발생할 수있는 DOM 삽입 지점에서 모두 수행된다. Modernizr 또는 jQuery에서 가능합니까?

내 목표는 리소스를 테스트에로드해야하는 DOM 요소를 삽입 할 수있는 잠재적 인 미래 포인트 이후에 테스트를 다시 선언하는 대신 모든 modernizr 테스트를 내 masterpage.js에 선언하는 것입니다.

답변

1

먼저 Modernizr.addTest()은 실제로 필요하지 않습니다 (래치되어 바람직하지 않은 동작이 발생할 수 있음). 당신은 간단하게 할 수 있습니다 :

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

DOM을 모니터하는 방법에 따라 아마 건너 뛸 수 있습니다.

$('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이 좋습니다. '# myid'가'

'요소의 하위 클래스로로드 된 경우에만 작업을 수행하려는 경우 livequery 함수에서 해당 조건을 테스트하는 것이 더 읽기 쉽습니다. –

+0

건배 Stu, 기본적으로 20 밀리 초마다 쿼리를 실행하는 것처럼 보일지라도 이것은 지금까지 최선의 선택 인 것 같습니다. 따라서 DOM 삽입 이벤트 (존재하지 않는 것으로 보임)에 응답하기보다는 선택기가 true가 될 때까지 기본적으로 확인합니다. – Tim

+0

[Mutation Observers] (http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers) - 지속적으로 쿼리하지 않고 DOM을 모니터링 할 수있는 일부 브라우저의 새로운 기능 - 사용할 수없는 경우 Livequery로 되돌아갑니다. 지원을 확인하는 방법은 다음과 같습니다. https://gist.github.com/stucox/5231211 –