Javascript 在其他任何事情之前加载特定图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7511352/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:33:10  来源:igfitidea点击:

load specific image before anything else

javascriptjqueryhtmlcss

提问by Shea

I'm a creating a loading screen for website I am making. The website loads many images, scripts, etc. The HTML and CSS part is great, but I need a way to guarantee that the "loading..." image will be loaded before anything else.

我正在为我正在制作的网站创建加载屏幕。该网站加载了许多图像、脚本等。HTML 和 CSS 部分很棒,但我需要一种方法来保证“正在加载...”图像将在其他任何事情之前加载。

I'm using jQuery, and everything is initiated within $(function () { ... });. I imagine that the code for this would need to be called before/outside that block, and the code to remove the loading screen will be called at the very end of that block. Currently, the loading image is set as a DIV background, which is the way I prefer it. However, if it's completely necessary, I will settle for an IMG tag.

我正在使用 jQuery,一切都在$(function () { ... });. 我认为需要在该块之前/之外调用此代码,并且将在该块的最后调用删除加载屏幕的代码。目前,加载图像设置为 DIV 背景,这是我更喜欢的方式。但是,如果完全有必要,我会选择 IMG 标签。

Update: (solution)

更新:(解决方案)

I was able to answer my own question by using a combination of Robin and Vlad's responses. Both were very good, and excellent answers, however the problem is that they were aimed to load an image before another image, rather than load an image before anything else. (CSS, JS, etc...)

通过结合使用 Robin 和 Vlad 的回答,我能够回答我自己的问题。两者都非常好,而且答案非常好,但是问题在于它们的目的是在另一个图像之前加载图像,而不是在其他任何图像之前加载图像。(CSS、JS 等...)

Here's the dirty version of what I came up with:

这是我想出的肮脏版本:

var files = [new Image(), document.createElement('link'), document.createElement('script')];
files[0].setAttribute('src', 'images/loading.gif');
files[1].setAttribute('rel', 'stylesheet');
files[1].setAttribute('type', 'text/css');
files[1].setAttribute('href', 'test.css');
files[2].setAttribute('type', 'text/javascript');
files[2].setAttribute('src', 'js/jquery-1.5.1.min.js');
window.onload = function (e) {
    document.getElementsByTagName('head')[0].appendChild(files[1]);
    document.getElementsByTagName('head')[0].appendChild(files[2]);
}

Taking a look at the load sequence on the network tab of Chrome's developer console shows that 'loading.gif' is loaded first, then 4 dummy images, then 'test.css', and then 'jquery.1.5.1.min.js'. The CSS and JS files don't begin to load, until they've been inserted into the head tag. This is exactly what I want.

查看 Chrome 开发者控制台网络选项卡上的加载顺序显示,首先加载“loading.gif”,然后是 4 个虚拟图像,然后是“test.css”,然后是“jquery.1.5.1.min.js” '。CSS 和 JS 文件不会开始加载,直到它们被插入到 head 标签中。这正是我想要的。

I'm predicting that I may begin to have some problems, however, when I begin to load a list of files. Chrome reports that sometimes the JS file is loaded first, but the majority of the time the CSS file is loaded first. This isn't a problem, except when I begin to add files to load, I will need to ensure that jQuery is loaded before a script file that uses jQuery.

我预测我可能会开始遇到一些问题,但是,当我开始加载文件列表时。Chrome 报告有时先加载 JS 文件,但大多数情况下先加载 CSS 文件。这不是问题,除非我开始添加要加载的文件时,我需要确保在使用 jQuery 的脚本文件之前加载 jQuery。

If anyone has a solution for this, or a way to detect when the CSS/JS files are finished loading, using this method, then please comment. Though, I'm not sure that it's going to be a problem yet. I may need to ask a new question in the future about this, if I start to run into problems.

如果有人对此有解决方案,或者使用此方法检测 CSS/JS 文件何时完成加载,请发表评论。不过,我不确定它是否会成为一个问题。如果我开始遇到问题,我将来可能需要就此提出一个新问题。

Thank you to every who has helped with this issue.

感谢所有帮助解决此问题的人。

Update: (glitch fix)

更新:(故障修复)

I ended up running into a lot of problem with this method, because the script files were being loaded asynchronously. If I would clear the browser cache, and then load the page, it would finish loading my jquery dependent files first. Then if I refreshed the page, it would work, because jquery was loaded from cache. I solved this by setting up an array of files to load, then putting the load script into a function. Then I would step through each array item using this code:

我最终遇到了这个方法的很多问题,因为脚本文件是异步加载的。如果我清除浏览器缓存,然后加载页面,它将首先完成加载我的 jquery 依赖文件。然后如果我刷新页面,它就会工作,因为 jquery 是从缓存加载的。我通过设置要加载的文件数组来解决这个问题,然后将加载脚本放入一个函数中。然后我将使用以下代码单步执行每个数组项:

element.onload = function() { 
    ++i; _step();
}
element.onreadystatechange = function() { 
    if (("loaded" === element.readyState || "complete" === element.readyState)) { ++i; _step(); }
}

采纳答案by Vlad Balmos

As long as the "loading..." image is positioned before any other html elements, it should load first. This of course depends on the size of the image. You could put the loading div right after the tag and position it using 'position:absolute'. Regarding the code to remove the loading screen, one method is to do the following.

只要“正在加载...”图像位于任何其他 html 元素之前,它就应该首先加载。这当然取决于图像的大小。您可以将加载 div 放在标签之后,并使用“position:absolute”定位它。关于移除加载屏幕的代码,一种方法是执行以下操作。

  • Put all the images, scripts that need to be loaded in a hidden div (display: none)
  • Set up a variable that will hold the total of the images / scripts to be loaded
  • Set up a counter variable
  • Attach to each image / script the "onload" event
  • Everytime the "onload" event is triggered it will call a function that will increment the counter variable and check if the value of the counter equals the value of the total variable
  • If all resources have been loaded, fire a custom event that will show the div with the images, and hide the div with the loading screen.
  • 把所有需要加载的图片、脚本放在一个隐藏的div中(显示:无)
  • 设置一个变量来保存要加载的图像/脚本的总数
  • 设置计数器变量
  • 将“onload”事件附加到每个图像/脚本
  • 每次触发“onload”事件时,它都会调用一个函数来增加计数器变量并检查计数器的值是否等于总变量的值
  • 如果所有资源都已加载,则触发一个自定义事件,该事件将显示带有图像的 div,并通过加载屏幕隐藏 div。

The code below isn't testes so it might not work. Hope it helps

下面的代码不是睾丸,所以它可能不起作用。希望能帮助到你

var totalImages = 0;
var loadCounter = 0;

function incrementLoadCounter() {
   loadCounter++;
   if(loadCounter === totalImages) {
      $(document).trigger('everythingLoaded');
   }
}

function hideLoadingScreen() {
   $('#loadingScreen').hide();
   $('#divWithImages').show();
}

$(document).ready(function(e) {
    $('#loadingScreen').bind('everythingLoaded', function(e) {
        hideLoadingScreen();
    });
    var imagesToLoad = $('img.toLoad');
    totalImages = imagesToLoad.length;

    $.each(imagesToLoad, function(i, item) {
        $(item).load(function(e) {
           incrementLoadCounter();
        })
    });
})

回答by VadimB

You can reuse resource prealoding browser support.

您可以重用资源预加载浏览器支持。

I'm not sure it works across all browsers but in my case this approach helps me to load images first. Also it allows to define concrete images so UI specific could be skipped

我不确定它是否适用于所有浏览器,但在我的情况下,这种方法可以帮助我首先加载图像。它还允许定义具体图像,因此可以跳过特定于 UI 的图像

First define in header what resource you want to preload and define resource priority

首先在 header 中定义要预加载的资源并定义资源优先级

<link rel="preload" href="link-to-image" as="image"> 

or

或者

<link rel="preload" href="link-to-image">

Second line allow to increase loading priority across all object types (scripts / images / styles). First line - only through images.

第二行允许增加所有对象类型(脚本/图像/样式)的加载优先级。第一行 - 仅通过图像。

Then define in body link to image as usual:

然后像往常一样在正文链接中定义图像:

<img src="link-to-image" alt="">

Here is my working example https://jsfiddle.net/vadimb/05scfL58/

这是我的工作示例 https://jsfiddle.net/vadimb/05scfL58/

回答by Robin Castlin

I'm not sure if it's possible to enforce.

我不确定是否可以强制执行。

If it is, try adding this in the head-tag:

如果是,请尝试将其添加到 head-tag 中:

<script type="text/javascript">
    if(document.images)
        (new Image()).src="http://www.image.com/example.png";
</script>

In theory that may load and cache that image before anything else.

从理论上讲,这可能会先加载和缓存该图像。

回答by PiTheNumber

I think if you place the IMG tag at the top of your html body it will be loaded first. If you do not want to move your div just use a copy of the image tag. Once the images is loaded it will be shown in every image tag which shows the same picture.

我认为如果您将 IMG 标签放在 html 正文的顶部,它将首先加载。如果您不想移动 div,只需使用图像标签的副本。加载图像后,它将显示在每个显示相同图片的图像标签中。

回答by Berend

Or you could use spin.js as loading image. It display this "loading cycle image" via javascript.

或者你可以使用 spin.js 作为加载图像。它通过javascript显示这个“加载周期图像”。

Check it out under: http://fgnass.github.com/spin.js/

在下面查看:http: //fgnass.github.com/spin.js/