简体   繁体   English

如何在JavaScript之前加载图片

[英]How to load image before javascript

I'm currently looking to improve the perception of a web application by ensuring that the company logo is downloaded ahead of the javascript. 我目前正在通过确保在javascript之前下载公司徽标来改善对Web应用程序的认知。

To do this I moved the javascript references below the img element for the company logo. 为此,我将javascript引用移到了公司徽标的img元素下方。

For example: 例如:

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

When looking at Google Chrome Developer Tools I can see that the call for the logo is made however it remains as "pending" until all the javascript on the page has been downloaded. 查看Google Chrome开发者工具时,我可以看到徽标的调用,但是在下载了页面上的所有JavaScript之前,徽标始终保持“待处理”状态。

Why is this happening? 为什么会这样呢? How can I ensure that the company logo is loaded ahead of the javascript? 如何确保将公司徽标加载到javascript之前?

Try to use $(window).load for your scripts if you're using jQuery. 如果您使用的是jQuery,请尝试对脚本使用$(window).load

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

According to the 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. 因此,与图像或其他页面内容有关的功能应放置在窗口或内容标签本身的加载事件中。

As for separate files that you have to add to your site using <script src='path/to/file'> , I recommend using $.getScript . 至于必须使用<script src='path/to/file'>添加到站点的单独文件,我建议使用$.getScript

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

Here is the $.getScript manual . 这是$.getScript 手册

Browser has to download and execute JS files as soon as one occurs during HTML markup parsing (at least due to possible usage of document.write in the scripts). 在HTML标记解析期间,浏览器必须下载并执行JS文件(至少是由于脚本中对document.write可能使用)。

One of the best solutions would be adding onload event handler which loads your script dynamically when page is ready: 最好的解决方案之一是添加onload事件处理程序,该处理程序会在页面准备就绪时动态加载脚本:

<script type="text/javascript">
window.addEventListener("load",function () {
    var elem = document.createElement("script");
    element.src = "file.js";
    document.body.appendChild(element);
, false);
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM