3
4

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.

脱jQuery化を試みて失敗した話

Last updated at Posted at 2019-12-19

各種ブラウザで使えるJavascriptが統一されてきたこともあり、ここらで自分が管理しているサイトからjQueryを除いてみようと思い試行錯誤をしていたが、結局諦めた。
これから同じような事をする人の参考になればと思い軽く情報共有しようと思う。

書き換え可能なもの

DOMの生成完了

//jquery
 $(document).ready(() => {})
//native
 document.addEventListener("DOMContentLoaded", () => {});

セレクタ(単数/複数)

//jquery
$('.className').each((index, elem) => {
//native
document.querySelector('.className')
document.querySelectorAll('.selected input').forEach((el, index) => {

属性情報の追加/取得

//jquery
$(elem).attr('attribute','value');
$(elem).attr('attribute');
//native
elem.setAttribute('attribute','value');
elem.getAttribute('attribute');

親要素のクラスを追加/除去
classListで要素に付与されているクラスのリストが取得可能

//jquery
$(elem).parent().addClass("className");
$(elem).parent().removeClass("className");
//native
elem.parentElement.classList.add('className');
elem.parentElement.classList.remove('className')

イベントリスナ

//jquery
$('hoge').click(() => {});
//native
document.querySelector('hoge').addEventListener('click', () => {}); //クラスが一つ
document.querySelectorAll('hoge').forEach((elem) => { //クラスが複数
  elem.addEventListener('click', () => {});
});

domが単数の場合と複数の場合を意識してコードを書かないといけないため結構面倒くさい。

困難なもの

・あるポジションまでAnimationで移動したい時

//jquery
const position = $("#id").offset().top;
$('html').animate({ scrollTop: position }, 'fast');
//native
const position = document.querySelector('#id').offsetTop;
window.scrollTo({
  top: position,
  behavior: "smooth"
});

一応アニメーションでのスクロール自体は実現することができるが、behaviorがsmoothかinstantぐらいの指定しかないため、気持ちの良いアニメーションを実現する事ができない。かといって自前でscroll書くのは結構大変で上手く書かないとコードも汚れる。

・script付きのhtmlを埋め込み実行

const html = '<div>...</div><script>...(some_js_execution)</script>'
//jquery
$('#id').html(html); // Scriptが実行される
//native
$('#id').innerHTML = html; // Scriptが実行されない

innerHTMLでは内部にscriptタグがある場合実行できない。ソーシャルボタンを設置する場合は大抵scriptタグがコピーされるソースの中に埋め込まれているので、動的な埋め込みが困難となる。jQueryではcreateElementをしてHTMLのDOMを生成してScriptタグを埋め込むという内部操作でScriptの実行を行っていたが、それを自前で書くのは面倒である。

まとめ

DOMの操作自体は比較的簡単に書けるが、複数DOMの操作は煩雑であった。また細かいAnimation制御ができなかったり、htmlとinnerHTMLなどのように微妙な違いが存在するものもあるので手軽に脱jQueryという訳には行かない事が分かった。

結局まだjqueryが役立つシーンは多いと思われる。Webサイト/Webアプリケーションのjavascriptの使用具合により
native javascriptのみ -> zepto + javascript -> jquery + javascript -> vue.js, react -> react + redux
ぐらいな感じで使い分けていくのが現状のベストプラクティスかなと個人的には思う。

3
4
2

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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?