動態載入jQuery的兩種方法執行個體分析,jquery執行個體分析

來源:互聯網
上載者:User

動態載入jQuery的兩種方法執行個體分析,jquery執行個體分析

本文執行個體講述了動態載入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程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.