javascript 如何在javascript和jquery中先加载一些东西
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13918170/
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 make something load first before another in javascript and jquery
提问by dramasea
I have a div with text in it and a background image. When I load the page the text always appear 1st(assume i have low speed internet connection). How can i make the background image load before text? Can You please give me solution in both jquery and javascript
我有一个带有文本和背景图像的 div。当我加载页面时,文本总是出现在第 1 位(假设我的互联网连接速度较低)。如何在文本之前加载背景图像?你能在 jquery 和 javascript 中给我解决方案吗
回答by Briguy37
Add the text in the onload event handlerfor the image.
在图像的onload 事件处理程序中添加文本。
Note: If you want to keep using a div
tag with a background image rather than an img
tag, you'll have to add the text during the window.onloadevent (see this answerfor the details).
注意:如果您想继续使用div
带有背景图像而不是img
标签的标签,则必须在window.onload事件期间添加文本(有关详细信息,请参阅此答案)。
回答by Nenotlep
Assuming your div looks like this:
假设您的 div 如下所示:
<div id="Derp" style="CSS-for-background-image-here">Magical ponies!</div>
I would try removing the text completely and then add this kind of jquery call:
我会尝试完全删除文本,然后添加这种 jquery 调用:
<script>
$(document).ready(function() {
$('#Derp').load(function() {
$('#Derp').text("Magical ponies!");
});
});
</script>
The $('#Derp').load(...)
is the key here. See the docs for load().It has an example of exactly what you need.
这$('#Derp').load(...)
是这里的关键。请参阅 load() 的文档。它有一个完全符合您需要的示例。
回答by user1026361
you could populate the content onload.
您可以在加载时填充内容。
Start with this:
从这个开始:
<div id="content"></div>
Then, in jquery, do this:
然后,在 jquery 中,执行以下操作:
$(document).ready(function() {
mybg= new Image();
mybg.onload=function(){
$('#content').html('YOURTEXTHERE');
}
mybg.src = "PATH/TO/IMG";
});
回答by Jai
your simple answer is .load
you can do when your window gets loaded fully and then text appears:
您的简单答案是.load
当您的窗口完全加载然后出现文本时您可以执行以下操作:
$(function(){
$(window).load(function() {
$('p').fadeIn(800);
});?
});
what this is doing is fading in the p tag with text
when whole window gets loaded
.
这是在做的事情是fading in the p tag with text
完整的window gets loaded
。
you can find a demo here: http://jsfiddle.net/a5P8b/
你可以在这里找到一个演示:http: //jsfiddle.net/a5P8b/