public
Created

Detection of whether the current script has been included synchronously or asynchronously

  • Download Gist
async.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
<!doctype html>
<html>
<head>
<title>Async</title>
</head>
<body>
<h1>Async</h1>
<script>
function loadScript(url, callback){
function cb(){
if (callback) callback()
}
var script = document.createElement('script')
if (script.readyState){
script.onreadystatechange = function(){
var rs = script.readyState
if (rs === 'loaded' || rs === 'complete'){
script.onreadystatechange = null
cb()
}
}
}else{
script.onload = function(){
cb()
}
}
script.src = url
document.getElementsByTagName('head')[0]
.appendChild(script)
}
 
loadScript('sync_or_async.js')
</script>
</body>
</html>
sync.html
HTML
1 2 3 4 5 6 7 8 9 10
<!doctype html>
<html>
<head>
<title>Sync</title>
</head>
<body>
<h1>Sync</h1>
<script src="sync_or_async.js"></script>
</body>
</html>
sync_or_async.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11
// Am I loaded sync or async?
 
var numScriptsBefore = document.getElementsByTagName('script').length
document.write('<script></script>')
var numScriptsAfter = document.getElementsByTagName('script').length
if (numScriptsBefore < numScriptsAfter)
console.log('I can document.write! (sync)')
else
console.log('I cannot document.write! (async)')
console.log('document.readyState: ' + document.readyState)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.