Skip to content

@airportyh /async.html
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Detection of whether the current script has been included synchronously or asynchronously
<!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>
<!doctype html>
<html>
<head>
<title>Sync</title>
</head>
<body>
<h1>Sync</h1>
<script src="sync_or_async.js"></script>
</body>
</html>
// 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.