<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>异步加载js文件</title>
<style type="text/css">
</style>
</head>
<body>
<div id='test'>1</div>
<script type="text/javascript">
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else { //Others: Firefox, Safari, Chrome, and Opera
script.onload = function() {
callback();
};
}
script.src = url;
document.body.appendChild(script);
}
var callback = function() {
console.log($('#test').html()); //1
}
loadScript('https://cdn.bootcss.com/jquery/3.2.1/jquery.js', callback);
</script>
<script type="text/javascript">
$('#test').html(); //报错
</script>
</body>
</html>