2011-12-22 3 views
0

내가 시도한 것

jQuery의 $.getScript은 두 가지를 수행하지만, 페이지에 추가하는 태그에 속성을 추가하는 방법을 모르겠습니다.속성이있는 js 파일을 어떻게 동적으로로드하고로드시 콜백을 실행합니까?

나는이 (: 그것은 커피 스크립트에있어 주) : 시도 위의와

$("<script>", {src: alohaScriptUrl, "data-aloha-plugins": alohaPlugins}) 
    .bind("load ready", onAlohaLoad) // also tried: .load(onAlohaLoad) 
    .appendTo("head") 

, 파일로드 거기에 적절한 태그는, 그러나 onAlohaLoad가 호출되지 않습니다.

파일을 동적으로로드하고 스크립트 태그에 속성을 넣고로드 할 때 콜백을 수행하려면 어떻게해야합니까??

여기에 내가하고 싶은에 대해 설명 커피 스크립트,하지만 그것은 작동하지 않습니다

$ -> 
    onAlohaLoad = -> 
    console.log("aloha loaded") 

    if localStorage["isAdmin"] == "true" 
    alohaScriptUrl = "/plugins/alohaeditor-0.20.0-RC9/lib/aloha.js" 
    alohaPlugins = "common/format" 
    $("<script>", {src: alohaScriptUrl, "data-aloha-plugins": alohaPlugins}) 
     .bind("load ready", onAlohaLoad) 
     .appendTo("head") 

답변

1

당신은 텍스트로 AJAX를 통해 가져오고 스크립트 태그의 innerHTML 속성 그것을 밖으로 수 있습니다. 그런 다음 (또는 후에) 추가하기 전에 스크립트 요소에 속성을 설정할 수 있습니다.

var xhr = new XMLHttpRequest(); 
xhr.open("GET", "test.js", true); 
xhr.send(null); 
xhr.onreadystatechange = function() { 
    if (xhr.readyState != 4) 
     return; 

    var script = document.createElement("script"); 
    script.innerHTML = xhr.responseText; 
    script.setAttribute(); //add attributes 
    document.body.appendChild(script); 

    console.log("callback!"); 
}; 
관련 문제