javascript 如何让脚本最后加载到网页上?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13846621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get a script to load last on webpage?
提问by wahle509
I have a webpage with mostly basic HTML on it. There is one section where I load an RSS feed using JavaScript pulling from an external source (url). The problem is that my page will load everything up until that script, wait for the script to load (sometimes up to a few seconds), then load the rest of the page.
我有一个网页,上面主要是基本的 HTML。有一个部分我使用 JavaScript 从外部源 (url) 中提取来加载 RSS 提要。问题是我的页面将加载所有内容直到该脚本,等待脚本加载(有时最多几秒钟),然后加载页面的其余部分。
How can I force it to load the script after it has rendered the entire page first?
在它首先呈现整个页面后,如何强制它加载脚本?
My code is something like this:
我的代码是这样的:
<html>
<more html>
<script language="JavaScript" src="http://..." type="text/javascript"></script>
<more html>
...
回答by Levi Botelho
Two options:
两种选择:
- Put your script block at the end of the page. This is good practice anyways due to the fact that your page strucutre will load before the script that is intended to manipulate it. Because the user generally notices the page loading but not the script, this gives the appearance of a faster load overall.
- Include the
defer
attribute in the openingscript
tag. Note thatdefer
can only be used on externalscript files (those with ansrc
attribute). See https://developer.mozilla.org/en-US/docs/HTML/Element/script.
- 将您的脚本块放在页面的末尾。无论如何,这是一个很好的做法,因为您的页面结构将在用于操作它的脚本之前加载。因为用户通常会注意到页面加载而不是脚本,所以总体上看起来加载速度更快。
defer
在开始script
标记中包含该属性。请注意,defer
只能用于外部脚本文件(具有src
属性的文件)。请参阅https://developer.mozilla.org/en-US/docs/HTML/Element/script。
回答by Amalgovinus
A pretty reliable way to make a script load after pageload is to write out the script include itself in javascript.
在页面加载后加载脚本的一种非常可靠的方法是将脚本包含在 javascript 中。
var theScript = document.createElement("script");
theScript.setAttribute("type","text/javascript");
theScript.setAttribute("src","//www.mysite.com/script.js");
document.getElementsByTagName("head")[0].appendChild(theScript);
回答by Shayna Diamond
You could try wrapping the function that calls the feed in
您可以尝试包装调用提要的函数
jQuery(window).load(function(){
//embed RSS feed
});
forcing it to load last.
强迫它最后加载。
回答by gpojd
Move your script tag to the end and it will load after everything else. For example:
将您的脚本标签移到最后,它将在其他所有内容之后加载。例如:
<html>
<more html>
<more html>
<script language="JavaScript" src="http://..." type="text/javascript"></script>
</html