Add và Load file js bằng javascript với callback event


Trường hợp bạn muốn add file *.js bằng javascript:

Hàm "loadScript" dưới đây sẽ add và load file js khi bạn gọi, với 2 tham số truyền vào là đường dẫn file *.js (sScriptSrc) và hàm sẽ đc thực thi khi file đc load xong (Callback func)


oScript.onreadystatechange on IE và oScript.onload on firefox browser.

function loadScript(sScriptSrc,callbackfunction)  
{ 
    //gets document head element 
    var oHead = document.getElementsByTagName('head')[0]; 
    if(oHead) 
    { 
        //creates a new script tag       
        var oScript = document.createElement('script'); 
                 
        //adds src and type attribute to script tag 
        oScript.setAttribute('src',sScriptSrc); 
        oScript.setAttribute('type','text/javascript'); 
 
        //calling a function after the js is loaded (IE) 
        var loadFunction = function() 
            { 
                if (this.readyState == 'complete' || this.readyState == 'loaded') 
                { 
                    callbackfunction();  
                } 
            }; 
        oScript.onreadystatechange = loadFunction; 
 
        //calling a function after the js is loaded (Firefox) 
        oScript.onload = callbackfunction; 
         
        //append the script tag to document head element         
        oHead.appendChild(oScript); 
    } 
}  


ví dụ dưới đây sẽ cho bạn hiểu thêm về hàm callback


var SuccessCallback = function(){ 
    fnInsideDynamicJs(); 
}

function fnInsideDynamicJs(){
    alert('fnInsideDynamicJs was called');
}

  

Khi button đc click, file "/js/requiredjsfile.js" sẽ đc add vào, khi load xong hàm fnInsideDynamicJS() sẽ được gọi.

Dịch từ: blog-logiclabz

Nhận xét

Bài đăng phổ biến từ blog này

Create self signed cerfiricate SSL