日期:2014-05-16  浏览次数:20273 次

script可以在页面全部加载前执行吗?
这段script代码总要等整个页面加载完毕才能执行,网页里有个气象预报的框架,加载很慢,总要等气象预报加载完毕才可以执行这段script代码。怎样让这段script代码提前加载:
HTML code

<script type="text/javascript">
window.onload = function() {
    var c = document.getElementById('controller').getElementsByTagName('td');
    var ar = ['http://www.baidu.com/s', 'http:m.baidu.com/m'];
    for(var i = 0; i < c.length; i ++) {
        c[i].onclick = function() {
            c[0].style.backgroundColor = '#FFF';
            c[1].style.backgroundColor = '#FFF';
            c[this.cellIndex].style.backgroundColor = '#0FF';
            document.getElementById('searcher').action = ar[this.cellIndex];
        }
    }
}
</script>
<table>
  <tr align="center" id="controller">
    <td style="background-color:#0FF"><a href="javascript:">网页</a></td>
    <td><a href="javascript:">音乐</a></td>
  </tr>
  <tr>
    <td colspan="2">
    <form action="http://www.baidu.com/s" target="_blank" id="searcher">
      <input name="word" type="text" value="" />
      <input type="submit" value="百度一下" />
    </form></td>
  </tr>
</table>
天气预报:
<iframe src="http://m.weather.com.cn/m/pn1/weather.htm " width="235" height="16" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no"></iframe>



------解决方案--------------------
iframe会阻塞页面加载
把<iframe src="http://m.weather.com.cn/m/pn1/weather.htm " width="235" height="16" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no"></iframe> 
的src去掉
在window.onload = function() {
var c = document.getElementById('controller').getElementsByTagName('td');
var ar = ['http://www.baidu.com/s', 'http:m.baidu.com/m'];
for(var i = 0; i < c.length; i ++) {
c[i].onclick = function() {
c[0].style.backgroundColor = '#FFF';
c[1].style.backgroundColor = '#FFF';
c[this.cellIndex].style.backgroundColor = '#0FF';
document.getElementById('searcher').action = ar[this.cellIndex];
}
}
}
中设置iframe的src
------解决方案--------------------
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
//这样试试
function changeSearcher(obj) {
    var c = document.getElementById('controller').getElementsByTagName('td');
    var ar = ['http://www.baidu.com/s', 'http://mp3.baidu.com/m'];
    for(var i = 0; i < c.length; i ++) c[i].style.backgroundColor = '#FFF';
    c[obj.cellIndex].style.backgroundColor = '#0FF';
    document.getElementById('searcher').action = ar[obj.cellIndex];
}
</script>
</head>

<body>
<table>
  <tr align="center" id="controller">
    <td style="background-color:#0FF" onclick="changeSearcher(this);"><a href="javascript:void(0);">网页</a></td>
    <td onclick="changeSearcher(this);"><a href="j