javascript - 如何在javascript之前加载图像

标签 javascript html performance perception

我目前正在寻求通过确保公司 Logo 在 JavaScript 之前下载来改善 Web 应用程序的感知。

为此,我将 JavaScript 引用移至公司 Logo 的 img 元素下方。

例如:

<img src="/Images/Logo.jpg" alt="My Company"/>
<script type="/Scripts/MyScripts.js"></script>

在查看 Google Chrome 开发者工具时,我可以看到对 Logo 的调用已发出,但它仍保持“待处理”状态,直到下载页面上的所有 javascript。

为什么会发生这种情况?如何确保公司 Logo 先于 JavaScript 加载?

最佳答案

尝试使用$(window).load如果您使用的是 jQuery,则适用于您的脚本。

$( window).load(function() {
    //put js code here
});

根据this site :

The window load event executes a bit later when the complete page is fully loaded, including all frames, objects and images. Therefore functions which concern images or other page contents should be placed in the load event for the window or the content tag itself.

至于您必须使用 <script src='path/to/file'> 添加到站点的单独文件,我建议使用 $.getScript .

$.getScript("path/to/file");

这是 $.getScript manual .

关于javascript - 如何在javascript之前加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28738525/

相关文章:

javascript - 如何使 event.srcElement 在 Firefox 中工作,它是什么意思?

javascript - 我怎样才能让它在弹出框中得到有效答案之前才开始

Javascript 网址管理

html - 如何删除 'press button' 效果并使按钮即使在单击时也变平

java - 哪个更快 : Cloning or using Streams?

javascript - MongoDB插入多个文档,其中可能有重复的_id

javascript - 如何在 lit-element 中实现 lit-element-bootstrap 包

html - 中间带有虚线文本的虚线分隔符

javascript - 如何使用 JavaScript 突出显示并保存 HTML 中的文本?

Python--从一个非空的multiprocessing.Queue中获取Queue.Empty异常