简体   繁体   中英

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.

To do this I moved the javascript references below the img element for the company logo.

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.

Why is this happening? How can I ensure that the company logo is loaded ahead of the javascript?

Try to use $(window).load for your scripts if you're using jQuery.

$( 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 .

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

Here is the $.getScript manual .

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).

One of the best solutions would be adding onload event handler which loads your script dynamically when page is ready:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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