【发布时间】:2013-11-14 02:47:17
【问题描述】:
我有一个显示高质量图片的页面。图片通常需要一段时间才能加载。我有一个在加载图片#image 时运行的 jQuery 函数我希望这个函数按照它们出现的顺序一次预加载其他图像 1。
所以:如果我在第一张图片上,它应该加载图片 1 并显示它,然后在 pic1 完成后预加载/缓存第二张图片。正在加载的图片都已经附加了一个缓存头。当 pic2 完成加载后, pic3 应该开始加载。如果您想知道,我有一个 cgi 后端,它可以循环打印东西等。
到目前为止,我有以下工作:
$('#image').load(function() {
preLoad2 = new Image()
preLoad2.src = "pic2"
})
然后我可以使用相同的$('#image').load(function() { } 行继续执行此操作,但我该如何制作才能使下一张图片在完全加载之前不会开始加载。我宁愿不使用定时延迟,因为这不是很准确。
这是我目前拥有的。我在这个例子中使用了一个 bash cgi 脚本。
#set a loop counter
# variables will be refered to as $[var-name]
count=1
first=true
#loop through all images that need pre-loading
for file in *
do
#check if the picture matches the search criteria
if [[ "$file" = *$lowerSearch* ]]
then
#create a js script
echo "<script language=\"javascript\" type=\"text/javascript\">"
echo "function load$count() {"
echo " preLoad$count = new Image()"
echo " preLoad$count.src = \"?loadFile=$file\""
echo "}"
#the first one of these functions should be bound to the main image load event
if [ "$first" = 'true' ]
then
echo "document.getElementById('image').onload = load$count()"
#the 2nd and on should be bound to the pre-load of the previous picture
else
echo " preLoad$last.onload = load$count()"
#end if
fi
echo "</script>"
#store the current count so that the next time through it can be used to call the last loaded picture
last=$count
first=false
#add 1 to count
count=$((count+1))
#end if
fi
#end loop
done
这是如何工作的:循环播放图片。如果图片符合搜索条件,则运行主代码...否则跳过循环。在搜索条件中,它创建一个包含函数的 js 脚本。该函数加载循环当前引用的图片。然后它创建一个 onLoad 函数,该函数引用最后一张预加载的图片,并为其设置一个 onLoad 事件以运行刚刚创建的函数。
我相信这个问题的答案和this question有些关系
【问题讨论】:
-
为什么不把图片放在容器里,设置一个loading.gif作为背景,让图片自己加载呢?
-
@elclanrs 我想优先考虑图片,以便按使用顺序加载它们。从正在显示的图片开始,它应该尽可能快地加载,而下一张图片应该在第一张图片加载后立即预加载。之后的图片应该加载下一个,它应该继续下去。
-
您可以使用延迟,链接回调来做到这一点。 api.jquery.com/category/deferred-object
-
我已对我的问题进行了编辑以显示更多我的代码。我使用了以下问题中的许多想法来创建上面显示的代码片段
标签: html javascript image jquery server-side-scripting