jQuery를 동적으로 로딩하는 두 가지 방법의 분석 예

PHPz
풀어 주다: 2018-09-29 15:22:44
원래의
838명이 탐색했습니다.

이 기사의 예에서는 jQuery를 동적으로 로드하는 두 가지 방법을 설명합니다. 참고할 수 있도록 모든 사람과 공유하세요. 자세한 내용은 다음과 같습니다.

첫 번째 방법은 이전에 이 사이트에 누군가가 게시한 코드를 참조하여 로딩 감지를 추가합니다.
두 번째 방법은 작년 12306 티켓 브러싱 스크립트에서 따왔습니다.

첫 번째 방법:

function withjQuery(callback) {
 if(!(window.jQuery)) {
 var js = document.createElement('script');
 js.setAttribute('src', 'https://dynamic.12306.cn/otsweb/js/common/jquery-1.4.2.min.js?version=5.47');
 js.setAttribute('type', 'text/javascript');
 js.onload = js.onreadystatechange = function() {
  if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') {
    if(callback && typeof callback === "function") {
     callback();
    }
   js.onload = js.onreadystatechange = null;
  }
 };
 document.getElementsByTagName('head')[0].appendChild(js);
 }
}
withjQuery( 
 function() { 
  $(function(){ alert("jQuery loaded"); })(); 
 }
);
로그인 후 복사

두 번째 방법:

// ==UserScript== 
// @name   12306 Booking Assistant
// @version  1.4.0
// @author  zzdhidden@gmail.com
// @namespace https://github.com/zzdhidden
// @description 12306 订票助手之(自动登录,自动查票,自动订单)
// @include  *://dynamic.12306.cn/otsweb/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript== 
function withjQuery(callback, safe){
 if(typeof(jQuery) == "undefined") {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
  if(safe) {
   var cb = document.createElement("script");
   cb.type = "text/javascript";
   cb.textContent = "jQuery.noConflict();(" + callback.toString() + ")(jQuery, window);";
   script.addEventListener('load', function() {
    document.head.appendChild(cb);
   });
  }
  else {
   var dollar = undefined;
   if(typeof($) != "undefined") dollar = $;
   script.addEventListener('load', function() {
    jQuery.noConflict();
    $ = dollar;
    callback(jQuery, window);
   });
  }
  document.head.appendChild(script);
 } else {
  setTimeout(function() {
   //Firefox supports
   callback(jQuery, typeof unsafeWindow === "undefined" ? window : unsafeWindow);
  }, 30);
 }
}
withjQuery(function($, window){
 $(function() { alert("jQuery loaded"); })();
}, true);
로그인 후 복사

이 기사가 모든 사람의 jquery 프로그래밍에 도움이 되기를 바랍니다. 더 많은 관련 튜토리얼을 보려면 jQuery 동영상 튜토리얼을 방문하세요.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!