![](/img/trans.png)
[英]What's Pros and Cons: putting javascript in head and putting just before the body close
[英]Putting Twitter Widget's Javascript within <Head> tags, but have it rendered in <Body>
我正在使用Twitter搜索小部件,目前我在HTML的body标签中嵌入了javascript,如下所示:
<body>
<script charset="utf-8" src="https://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
version: 2,
type: 'faves',
rpp: 1,
interval: 7200000,
title: '',
subject: '',
width: 500,
height: 65,
theme: {
shell: {
background: '#a4c9b9',
color: '#ffffff'
},
tweets: {
background: '#a4c9b9',
color: '#ffffff',
links: '#444444'
}
},
features: {
scrollbar: true,
loop: false,
live: false,
behavior: 'all'
}
}).render().setUser('exampleuser').start();
</script>
</body>
相反,我宁愿将所有javascript移动到标题(或者可能是页脚?)标记,然后只是在没有标记的情况下将其渲染到正文中。 有一个简单的方法吗?
你可以使用其中一个本机JS ...
window.onload = function() {
// your code here
};
或者jQuery ......
$(document).ready(function() {
// your code here
});
...确保代码在文档加载完成之前不会运行。
这解释了window.onload和$(document).ready()之间的细微差别。
另一个选择是将代码包装在一个命名函数中并在某个地方调用它,但你仍然需要将它放在<script>标记中。
编辑:使用window.onload ...
<html>
<head>
<script>
window.onload = function() {
new TWTR.Widget({
version: 2,
type: 'faves',
rpp: 1,
interval: 7200000,
title: '',
subject: '',
width: 500,
height: 65,
theme: {
shell: {
background: '#a4c9b9',
color: '#ffffff'
},
tweets: {
background: '#a4c9b9',
color: '#ffffff',
links: '#444444'
}
},
features: {
scrollbar: true,
loop: false,
live: false,
behavior: 'all'
}
}).render().setUser('exampleuser').start();
};
</script>
</head>
<body></body></html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.