2013-09-07 1 views
7

HTML5에서 자바 스크립트의 대체 소스를 사용할 수 있습니까? 예를 들어 jQuery를 사용하고 있으며 로컬로 가져 왔습니다. 그러나 alt 속성을 포함 할 수 있으므로 작동하지 않으면 Google의 jQuery가로드됩니까? 그것이 작동하는 경우스크립트의 대체 소스를 사용할 수 있습니까?

코드는 다음과 같이 보일 것입니다 : <script src="enter your text here.js" alt="googlescode"></script>

+0

자바 스크립트로 작성된 많은 스크립트 로더가 위치 :에

은 기본적으로 위의 코드 변환합니다. 정적 HTML 솔루션을 원한다고 가정해야합니까? –

+0

물론, 그게 내 질문에 관한 것이 아닙니다. – tjons

답변

5

jQuery 인 경우 this article을 참조하십시오.

발췌문 :

<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script> 
<script> 
    if (typeof jQuery == 'undefined') { 
     document.write(unescape("%3Cscript src='/js/jquery-2.0.0.min.js' type='text/javascript'%3E%3C/script%3E")); 
    } 
</script> 
5

예, 당신이 그것을 할 수 있습니다. HTML5 Boilerplate에는 jQuery 로딩에 대한 좋은 예가 있습니다.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script> 

하지만 다른 방법으로 사용합니다. google에서 스크립트를로드 할 수 없으면 로컬 스크립트로 돌아갑니다.

"로컬"버전보다 빨리로드되므로 CDN 버전을 먼저로드해야합니다.

+0

내 컴퓨터에서 로컬로드가 훨씬 빨라졌습니다. – tjons

+4

로컬 호스트에로드하는 경우 물론 더 빠르지 만 실제 프로덕션 환경에서는 그렇지 않습니다.이 문서의 장점을 설명하는이 문서를 읽을 수 있습니다. http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/ – Sebsemillia

1

나는 모든 이전의 답변 크롬 document.write 때문에 느린 연결로를 차단 공통의 문제를 가지고 실현을 구현하는 동기 기능입니다. 문제는 this post에서 논의됩니다.

일반적으로 솔루션은 현대식 로더를 사용하거나 js 코드를 미리 컴파일합니다.

그러나 유스 케이스에 여전히이 방법이 필요한 경우 비동기 호출을 사용해야합니다. 예시적인 예는 the way Google Analytics is loaded입니다.

<script>window.jQuery || (function(){ 
     // Create the DOM node 
     a=document.createElement('script'); 
     a.src="http://path-to-the-script.js"; 
     a.async=1; 
     // Find a node, and insert the script before it 
     m=document.getElementsByTagName('script')[0]; 
     m.parentNode.insertBefore(a,m); 
    })()</script> 
관련 문제