vanilla js 에서 ajax 로 불러온 js소스를 실행시키기 > IT 기술백서

IT 기술백서

직접 알아내거나 검색하기 귀찮아서 모아 둔 것

JavaScript | vanilla js 에서 ajax 로 불러온 js소스를 실행시키기

본문

ajax로 불러온 javascript 소스를 실행하는 방법이다. 

jQuery 에서는 $.load() 함수를 쓰면 불려온 자바스크립트가 자동으로 실행이된다.

이제는 jQuery를 서서히 벗어나야 하는데 몰라서 한참 헤멧다.  편한 라이브러리만 썼던게 함정 ㅜㅜ

핵심은 (new Function(소스))(); 이다.

 

[code]

 (function() {

    const httpRequest = new XMLHttpRequest();


    if (!httpRequest) return


    httpRequest.onreadystatechange = changeHandler

    httpRequest.open('GET', '//xxx.co.kr/source.php');

    httpRequest.send();

    

    function changeHandler() {

        var DONE =  (typeof XMLHttpRequest.DONE !== 'undefined') ? XMLHttpRequest.DONE : 4;


        if (httpRequest.readyState === DONE) {

            if (httpRequest.status !== 200) return

            

            var src = httpRequest.response;

            (new Function(src))();

        }

    }

})();

[/code]

댓글 0개

등록된 댓글이 없습니다.

Menu