2013-05-24 17 views
9

Làm cách nào tôi có thể nhận được cuộc gọi lại không chạy cho đến khi tập lệnh thực sự được thêm vào tài liệu?Gọi lại trễ cho đến khi tập lệnh được thêm vào tài liệu?

function addScript(filepath, callback){ 
    if (filepath) { 
     var fileref = document.createElement('script'); 
     fileref.setAttribute("type","text/javascript"); 
     fileref.setAttribute("src", filepath); 
     if (typeof fileref!="undefined") 
      document.getElementsByTagName("head")[0].appendChild(fileref); 
    } 
    if (callback) { 
     callback(); 
    } 
} 

Trả lời

12

Trong thế giới lý tưởng, bạn có thể sử dụng tài sản của onload thẻ <script />;

function addScript(filepath, callback){ 
    if (filepath) { 
     var fileref = document.createElement('script'); 

     fileref.onload = callback; 

     fileref.setAttribute("type","text/javascript"); 
     fileref.setAttribute("src", filepath); 

     if (typeof fileref!="undefined") 
      document.getElementsByTagName("head")[0].appendChild(fileref); 
    } 
} 

Tuy nhiên, this doesn't work in IE, vì vậy cần phải có mega-h4x;

function addScript(filepath, callback) { 
     if (filepath) { 
      var fileref = document.createElement('script'); 
      var done = false; 
      var head = document.getElementsByTagName("head")[0]; 

      fileref.onload = fileref.onreadystatechange = function() { 
       if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) { 
        done = true; 

        callback(); 

        // Handle memory leak in IE 
        fileref.onload = fileref.onreadystatechange = null; 
        if (head && fileref.parentNode) { 
         head.removeChild(fileref); 
        } 
       } 
      }; 

      fileref.setAttribute("type", "text/javascript"); 
      fileref.setAttribute("src", filepath); 

      head.appendChild(fileref); 
     } 
    } 

FWIW, if (typeof fileref != "undefined") của bạn là không cần thiết, vì nó sẽ luôn luôn đánh giá đúng, vì vậy bạn chỉ có thể làm head.appendChild(fileref); trực tiếp, như trong ví dụ của tôi.

-1

Cách dễ nhất sẽ được xác định một số chức năng hiển thị động, ở cuối.

+1

tôi không thể chạm vào kịch bản tự động bao gồm. – dezman

2

gì về:

var myParticularCallback = function() { 
    // do something neat ... 
} 

..... your code 

var fileref = document.createElement('script'); 
fileref.setAttribute("type","text/javascript"); 

fileref.onload = myParticularCallback; 

if (typeof fileref!="undefined") 
    document.getElementsByTagName("head")[0].appendChild(fileref); 

// after all has set, laod the script and wait for onload event: 
fileref.setAttribute("src", filepath); 
+0

Thực sự thích giải pháp sử dụng fileref.onload = myParticularCallback –

Các vấn đề liên quan