Last active
August 29, 2015 14:06
-
-
Save takamin/d39bf8ccff805baecb1b to your computer and use it in GitHub Desktop.
jqueryが読み込まれる前のSCRIPTでjqueryが使えるようになるまで待つ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- load a gist directly by using RawGit --> | |
<script | |
type="text/javascript" | |
src="https://cdn.rawgit.com/takamin/d39bf8ccff805baecb1b/raw/faf22f4f507673ce3143b82ee842dcf5b2130c2a/wait_jquery.js" | |
></script> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var jq_callbacks = []; | |
function $(callback) { // (^^; | |
jq_callbacks.push(callback); | |
} | |
(function() { | |
// jQueryが使えるようになるまで待つ | |
var check_count_max = 100; | |
var check_count = 0; | |
var wait_jquery = function () { | |
window.setTimeout(function() { | |
try { | |
if(jQuery) { | |
for(var i = 0; i < jq_callbacks.length; i++) { | |
jq_callbacks[i].call(null, jQuery); | |
} | |
} else { | |
throw "no jquery"; | |
} | |
} catch(e) { | |
check_count++; | |
if(check_count < check_count_max) { | |
wait_jquery(); | |
} else { | |
$ = null; | |
for(var i = 0; i < jq_callbacks.length; i++) { | |
jq_callbacks[i].call(null, null); | |
} | |
} | |
} | |
}, 300); | |
} | |
wait_jquery(); | |
}()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- sample --> | |
<div id="wait_jquery_status" class="jquery_available" | |
style="width:100%; padding:10px; font-weight:bold; | |
font-size:16pt; text-align:center; color:white; | |
background-color:red;" | |
>ちょっと待ってね♪ jQueryの読み込みを待っています・・・</div> | |
<script> | |
try { | |
//$ is NOT a jQuery | |
$(function(){ | |
if($ == null) { | |
throw('timeout') | |
} | |
//this one is a jQuery | |
$('.jquery_available') | |
.css('background-color', 'blue') | |
.html('お待たせしました♪ jQueryが利用可能です'); | |
}); | |
} catch (e) { | |
var e = document.getElementById("wait_jquery_status"); | |
e.parentNode.removeChild(e); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment