jQuery iframeの読み込み完了後のタイミングで処理を実行する方法

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんばんは。Toshikuraです。今回のTipsは【jQuery iframeの読み込み完了後のタイミングで処理を実行する方法】です。局所的な記事が続いていますが地味に使えるTipsなのでメモしておきます。デモの方を見ていただければざっくりとした使い方が掴めるかと思います。もしよろしければ合わせてご確認ください。

iframeの読み込み完了後のタイミング

読み込みのタイミングで何らかの動作をさせる場合は以下のような記述で実装可能です。
 
HTML


<iframe id="tgt" src="http:****.com"></iframe>

JS

<script type="text/javascript">
$(‘#tgt’).load(function(){
console.log(‘読み込み完了’);
});
</script>

クリック等のタイミングで読み込み

次の例はクリック等のタイミングでiframeの読み込みを開始させ、且つiframeの読み込みの完了を取得します。
 
JS


<script type="text/javascript">
$(function(){
var url = ‘http:****.com’;//読み込み先のURL
$(‘#loadbtn’).click(function(){
$(‘#tgt’).attr({‘src’:url});
$(‘#tgt’).load(function(){
console.log(‘読み込み完了’);
});
});
});
</script>

クリック等のタイミングで読み込み(デモ)

今回のデモではこれに加え、ローディングイメージ及びiframe自身の表示・非表示を行っています。
 
CSS


#tgt{display: none;}
#loading{display: none;}

HTML

<img src="images/loading.gif" id="loading">
<iframe id="tgt" src=""></iframe>

JS

<script type="text/javascript">
$(function(){
var url = ‘http:****.com’;//読み込み先のURL
$(‘#loadbtn’).click(function(){
$(‘#loading’).fadeIn(300);
$(‘#tgt’).attr({‘src’:url});
$(‘#tgt’).load(function(){
$(this).fadeIn(1000);
$(‘#loading’).fadeOut(300);
});
});
});
</script>

 
以上になります。