26
30

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.

外部jsのロードが完了してからfunctionを実行する

Posted at

外部js内に関数が定義されていて、それが定義されてから実行する方法。
document.writeなどで動的にscriptタグが書き出されたときに、scriptの実行順序が逆になっても対応が可能。

javascript
// src: 外部jsのパス
// handler: jsのロード完了後に実行する関数
var call = function(src, handler){
	var base = document.getElementsByTagName("script")[0];
	var obj = document.createElement("script");
	obj.async = true;
	obj.src= src;
	if(obj.addEventListener){
		obj.onload = function () {
		handler();
		}
	}else{
		obj.onreadystatechange = function () {
			if ("loaded" == obj.readyState || "complete" == obj.readyState){
				obj.onreadystatechange = null;
				handler();
			}
		}
	}
	base.parentNode.insertBefore(obj,base);
};

call("http:xxxxxxx/xxx.js", function(){/*ここに処理を記載*/})
26
30
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
26
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?