8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【個人メモ】Bookmarkletを使って新しいバージョンのjQueryをOverrideしたい

Posted at

動機

Bookmarkletを作りたいときに、すでに用意されている既存サイトで
ロードされちゃってる古いjQueryを新しいVersionにoverrideしたい。

$.parseHTMLが使えない環境とかと遭遇したのでメモしとく。
($.parseHTMLはjQuery 1.8から利用できる...)

動作確認環境

  • Mac OS X 10.10
  • Google Chrome Version 38.0.2125.111

古いjQueryライブラリがロードされている状態

1.11.1をロードしている状態だとする

<!DOCTYPE html>
<html>
  <head>
  <script src='http://code.jquery.com/jquery-1.11.1.min.js'></script>
  </head>
  <body>
    <div>
      <script type="text/javascript">
        console.log('jQuery version is: ' + $.fn.jquery);
      </script>
    </div>
  </body>
</html>

console.logの出力結果は、1.11.1となっている

Screen Shot 2014-11-05 at 14.46.51.png

新しいバージョンのjQueryをロードしたい!

って場合は上書きするわけだけど、
まあ$を無効にしなければいけないから、
**$.noConflict()**を実行する。

例としてBookmarkletで上書きしたい場合を示す

以下のBookmarkletを用意する

(function() {
  function getJQueryVersion() {
    console.log('$.fn.jquery : ' + $.fn.jquery);
  }

  var jq = document.createElement('script');
  jq.src = 'http://code.jquery.com/jquery-2.1.1.min.js';
  jq.onload = getJQueryVersion;
  console.log('jQuery.fn.jquery : ' + jQuery.fn.jquery);
  $.noConflict();
  document.body.appendChild(jq);
})();

minifyしたものを用意する

((function(){function e(){console.log("$.fn.jquery version: "+$.fn.jquery)}var t=document.createElement("script");t.src="http://code.jquery.com/jquery-2.1.1.min.js";t.onload=e;console.log(jQuery.fn.jquery);$.noConflict();document.body.appendChild(t)})());

Bookmarkletとして、ブックマークに追加する

ChromeのBookmarkmanager(chrome://bookmarks/)で登録する

javascript:(function(){function e(){console.log("$.fn.jquery version: ");console.log($.fn.jquery)}var t=document.createElement("script");t.src="http://code.jquery.com/jquery-2.1.1.min.js";t.onload=e;console.log(jQuery.fn.jquery);$.noConflict();document.body.appendChild(t)})()

実行してみる

Screen Shot 2014-11-05 at 15.23.19.png

**$**が新しいバージョンのものに上書きされたことがわかった。

Bookmarkletで新しいjQueryバージョンのものを使いたい場合

  1. DOMとして突っ込む
  2. $.noConflict(); を呼び出す
  3. document.createElemnet('script').onloadに、jQueryリソースロード後のフック関数を用意しておく

こんな感じだろうか。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?