写JavaScript时,加载顺序是非常关心的,下面的一个脚本演示了加载的顺序:
演示地址:
http://phpor.net/projects/js/test_async.js.php?m=a
http://phpor.net/projects/js/test_async.js.php?m=b
http://phpor.net/projects/js/test_async.js.php?m=c
http://phpor.net/projects/js/test_async.js.php?m=d
http://phpor.net/projects/js/test_async.js.php?m=e
—————————test_async.js.php
<?php
if(isset($_GET[‘js2’])){
sleep(1);
echo "alert(‘outer2 js’);";
exit();
}
if(isset($_GET[‘js’])){
//sleep(1);
echo ‘document.write(\'<script src="?js2"></script>\’);’;
echo "alert(‘outer js’);";
exit();
}
if($_GET[‘m’] == ‘a’){
echo ‘<script src="?js"></script>’;
echo ‘<script> alert("inner js"); </script>’;
} else if($_GET[‘m’] == ‘b’){
echo ‘<script>document.write(\'<script src="?js"><\/script>\’);alert("inner js");</script>’;
} else if($_GET[‘m’] == ‘c’){
echo ‘<script>document.write(\'<script src="?js"><\/script>\’);</script><script>alert("inner js");</script>’;
} else {
?>
<script>
var loadScript = function (id, scriptSource, charset) {
var head = document.getElementsByTagName(‘head’)[0];
var oldScript = document.getElementById(id);
if (oldScript) {
head.removeChild(oldScript);
}
var newScript = document.createElement(‘script’);
if (charset) {
newScript.charset = charset;
} else {
newScript.charset = ‘gb2312’;
}
newScript.id = id;
newScript.type = ‘text/javascript’;
newScript.src = scriptSource;
head.appendChild(newScript);
};
</script>
<?php
if($_GET[‘m’] == ‘d’) {
echo ‘<script >loadScript("scriptid","?js");</script>’;
echo ‘<script> alert("inner js"); </script>’;
} else if($_GET[‘m’] == ‘e’){
echo ‘<script >loadScript("scriptid","?js");alert("inner js");</script>’;
}
}
?>
——————————————————