Skip to content

Instantly share code, notes, and snippets.

@airportyh
Created February 23, 2012 04:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airportyh/1889980 to your computer and use it in GitHub Desktop.
Save airportyh/1889980 to your computer and use it in GitHub Desktop.
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