13
1

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.

script タグを動的に削除しても、スクリプトは動作するのだろうか

Posted at

気になったので、確かめてみました。
script タグを動的に削除しても、スクリプトは動作し続けるのだろうか、と。

結論から言うと、スクリプトは動作します。タグを削除しても、メモリ上にあるオブジェクトや関数は削除されるわけではないので、当たり前といえば当たり前です。

以下、動作確認用の HTML です。

<html>
<body>
<button id="button1" type="button">test1</button>
<button id="button2" type="button" onclick="handler()">test2</button>
<script id="jquery" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
	jQuery("#button1").click(handler);
});

function handler(){
	alert(jQuery("script").length);
	jQuery("script").remove();
}
</script>
</body>
</html>

ボタンが2つありますが、いずれをクリックしても、呼び出される関数handler() は同じです。動作は同じですが、関数の紐づけ方が異なり、片方は jQuery でイベントハンドラを登録し、片方は onclick 属性を使用しています。

関数では、script タグの数をダイアログで表示した後、script タグを全て削除しています。

2つのボタン、どちらをクリックしても、動作し続けます。最初の1回目だけ 2 とダイアログに表示され、後は 0 です。初回で script タグは削除されてしまうからです。

13
1
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
13
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?