jQuery.getScript( url [, success ] ) > 개발자팁

개발자팁

개발과 관련된 유용한 정보를 공유하세요.
질문은 QA에서 해주시기 바랍니다.

jQuery.getScript( url [, success ] ) 정보

jQuery jQuery.getScript( url [, success ] )

본문

jQuery.getScript( url [, success ] )

 

설명 : GET HTTP 요청을 사용하여 서버에서 JavaScript 파일을로드 한 다음 실행하십시오.

$.ajax({
  url: url,
  dataType: "script",
  success: success
});

스크립트는 전역 컨텍스트에서 실행되므로 다른 변수를 참조하고 jQuery 함수를 사용할 수 있습니다. 포함 된 스크립트는 현재 페이지에 영향을 줄 수 있습니다.

성공 콜백
스크립트가로드되었지만 반드시 실행되지는 않으면 콜백이 시작됩니다.

스크립트는 파일 이름을 참조하여 포함되고 실행됩니다.

$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  console.log( data ); // Data returned
  console.log( textStatus ); // Success
  console.log( jqxhr.status ); // 200
  console.log( "Load was performed." );
});
오류 처리
jQuery 1.5부터는 .fail()오류를 설명 하는 데 사용할 수 있습니다 .

$.getScript( "ajax/test.js" )
  .done(function( script, textStatus ) {
    console.log( textStatus );
  })
  .fail(function( jqxhr, settings, exception ) {
    $( "div.log" ).text( "Triggered ajaxError handler." );
});
jQuery 1.5 이전에는 오류 .ajaxError()를 처리하기 위해 전역 콜백 이벤트를 사용해야했습니다 $.getScript().


$( "div.log" ).ajaxError(function( e, jqxhr, settings, exception ) {
  if ( settings.dataType == "script" ) {
    $( this ).text( "Triggered ajaxError handler." );
  }
});
응답 캐싱
기본적으로 $.getScript()캐시 설정을로 설정합니다 false. 이렇게하면 요청 URL에 timestamped 쿼리 매개 변수가 추가되어 요청할 때마다 브라우저에서 스크립트를 다운로드합니다. 다음을 사용하여 cache 속성을 전역으로 설정하여이 기능을 무시할 수 있습니다 $.ajaxSetup().


$.ajaxSetup({
  cache: true
});
또는 더 유연한 $.ajax()방법 을 사용하는 새 메서드를 정의 할 수 있습니다.

예 :
캐시 된 스크립트를 가져올 수있는 $ .cachedScript () 메서드를 정의하십시오.

jQuery.cachedScript = function( url, options ) {
 
  // Allow user to set any option except for dataType, cache, and url
  options = $.extend( options || {}, {
    dataType: "script",
    cache: true,
    url: url
  });
 
  // Use $.ajax() since it is more flexible than $.getScript
  // Return the jqXHR object so we can chain callbacks
  return jQuery.ajax( options );
};
 
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
  console.log( textStatus );
});

부하 공식 jQuery를 컬러 애니메이션 플러그인을 동적으로 새로운 기능이로드되면 발생하는 몇 가지 컬러 애니메이션을 결합한다.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getScript demo</title>
  <style>
  .block {
     background-color: blue;
     width: 150px;
     height: 70px;
     margin: 10px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<button id="go">» Run</button>
<div class="block"></div>
 
<script>
var url = "https://code.jquery.com/color/jquery.color.js";
$.getScript( url, function() {
  $( "#go" ).click(function() {
    $( ".block" )
      .animate({
        backgroundColor: "rgb(255, 180, 180)"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "olive"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "#00f"
      }, 1000 );
  });
});
</script>
 
</body>
</html>

추천
0

댓글 0개

전체 5,352
개발자팁 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT