■html内
<script type="text/javascript" src="test.js"></script>
■test.js
var head = document.getElementsByTagName("head");
var script = document.createElement("script");
script.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js");
script.setAttribute("type","text/javascript");
document.head.appendChild(script);
$(function(){
alert('test');
});
結果としては、
http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js
を読み込むよりも先に
$(function(){
alert('test');
});
が読まれてしまい
「ReferenceError: $ is not defined」
というエラーがでます。
setTimeout()を使い遅らせる事で実行は成功しますが、それ以外で実行できる方法があれば教えて頂きたいです。
宜しくお願い致します。
ぼくなら、script の onload を使います。
var head = document.getElementsByTagName("head"); var script = document.createElement("script"); script.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"); script.setAttribute("type","text/javascript"); // ★これ script.addEventListener("load", function() { $(function(){ alert('test'); }); }); document.head.appendChild(script);
window.onload - Web API インターフェイス | MDN
window.onloadか
DOMContentLoaded - Event reference | MDN
DOMContentLoadedを利用してみてはいかがでしょうか。
window.addEventListener("DOMContentLoaded", function(){ $(function(){ alert('test'); ); }, false);
ぼくなら、script の onload を使います。
var head = document.getElementsByTagName("head"); var script = document.createElement("script"); script.setAttribute("src","http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"); script.setAttribute("type","text/javascript"); // ★これ script.addEventListener("load", function() { $(function(){ alert('test'); }); }); document.head.appendChild(script);
回答ありがとうございます。
このやり方で解決しました。
回答ありがとうございます。
2015/05/12 19:58:21このやり方で解決しました。