在HTML中包含js文件

时间:2009-01-22 07:34:36

标签: javascript header

我在HTML中包含了一个巨大的javascript文件(500K)。有没有一种聪明的方法来知道它是否已被加载。我能想到的一种方法是在其构造函数中有一个变量来初始化并通知我。加载是异步的,我不能继续,直到包含该JS的函数。

由于

6 个答案:

答案 0 :(得分:6)

通过使用jQuery,您可以处理在加载脚本文件时运行的回调函数:

$.getScript("yourScriptFile.js", function(){
  // What to do when the script is loaded
});

Docs

答案 1 :(得分:3)

作为对奥斯卡回答的澄清:

<script type='text/javascript' src='script.js'></script>
<script type='text/javascript'>
 alert('the file has loaded!'); 
 //Anything here will not be executed before the script.js was loaded
</script>

此外,如果文件很大,最好在页面加载后加载它,这样你在慢速连接时可以在加载页面之前使用该页面:

<head>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
 Nothing here will be rendered until the script has finished loading
</body>

更好的是:

<head>
</head>
<body>
 I will be rendered immidiatly
</body>
<script type='text/javascript' src='script.js'></script>
</html>

这样用户可以快速获取页面,然后才能等待javascript功能。

答案 2 :(得分:0)

<SCRIPT LANGUAGE="JavaScript" SRC="filename">
</SCRIPT>

...

答案 3 :(得分:0)

您是否尝试过压缩javascript文件?将一些功能移动到单独的Javascript文件中,并且只包含所需的javascript?

答案 4 :(得分:0)

您可以在脚本文件的末尾调用一个函数,该函数会通知页面上的脚本已准备好使用。

答案 5 :(得分:0)

也许问题可能会被重述:我怎么知道我的脚本是在html页面中加载的?将脚本放在页面底部,确保脚本可以使用所有DOM元素。当您想知道脚本是否可用时,应检查要运行的函数是否可用。也许这个构造函数可以提供帮助:

function Wait(what,action,id){
 var _x = this,
     rep = document.getElementById('report'),
     cnt = 0,
     timeout = 5,
     interval = 100;

  _x.id = id;

  if (!(what instanceof Function)) {
   return true; //or say something about it
  }

  function dowait() {
   cnt += interval;
   if (what())
   {
      clearInterval(_x.iv);
      action();
      return true;
   }
   if (cnt>(timeout*1000))
   {
      clearInterval(_x.iv);
          //[do some timeout-action]
      return true; 
   }
 }
 _x.iv = setInterval(dowait,interval);

}

构造函数接受一个函数(返回一个布尔值)作为它的第一个参数。像

function(){return document.getElementById('someelement').innerHTML = '';}

因此,如果您在javascript之前添加此内容,则可以执行以下操作:

var testfn = 
     function(){return document.getElementById('someElement').innerHTML = '';},
   callback = 
     function(){alert('someElement is empty')},
   dummy = null;
window.onload=function(dummy=new Wait(testfn,calllback);