首頁 > web前端 > js教程 > 主體

動態載入jQuery的兩種方法實例分析

PHPz
發布: 2018-09-29 15:22:44
原創
839 人瀏覽過

本文實例講述了動態載入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學習者快速成長!