Created
February 23, 2012 04:03
-
-
Save airportyh/1889980 to your computer and use it in GitHub Desktop.
Detection of whether the current script has been included synchronously or asynchronously
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
<!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> |
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
<!doctype html> | |
<html> | |
<head> | |
<title>Sync</title> | |
</head> | |
<body> | |
<h1>Sync</h1> | |
<script src="sync_or_async.js"></script> | |
</body> | |
</html> |
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
// 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