1.inline event: html tag on+事件类型
<开始标签 on+事件类型=“js代码”></结束标签>
2.embeded script:head中添加<script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script>
window.onload = function () {
alert('你好')
}
</script>
</head>
<body>
</body>
</html>
3. js source file:在head标签中写一个链接src,类似css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="one.js"></script>
</head>
<body>
</body>
</html>
4.通过DOM添加:
var js=document.createElement("script");
js.src="xxx.js";
<script type="text/javascript">
var script = document.createElement("script");
script.src = "http://xxx.xx/xx.js";
document.getElementsByTagName('head')[0].appendChild(script);
</script>
jQuery中封装了这种方式,并加入了回调:$.getScript(url,callback(res, status));
简单实现如下:
var getScript = function(url, callback) {
var js = document.createElement('script');
js.setAttribute('type', 'text/javascript');
js.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(js);
if(callback && typeof callback == 'function'){
if (document.all) { //IE
js.onreadystatechange = function() {
if(js.readyState == 'loaded' || js.readyState == 'complete'){
callbackFn();
}
}
}else{
js.onload = function() {
callbackFn();
}
}
}
}