1

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?

Curtis
  • 101,612
  • 66
  • 270
  • 352

2 Answers2

1

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.

Zaenille
  • 1,384
  • 9
  • 16
  • Thanks Mark, are you suggesting that I move all my javascript references into a javascript call in the window load trigger? – Curtis Feb 26 '15 at 10:03
  • @Curt, yes, for your page scripts. If you also want the other javascript files that you import from separate files to be loaded after, then I recommend using `$.getScript`. I edited it into my question. – Zaenille Feb 26 '15 at 10:37
0

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>
cyberskunk
  • 1,722
  • 20
  • 22
  • `as soon as one occurs during HTML markup` My image is defined above the script though. Why isn't this downloaded first? – Curtis Feb 26 '15 at 10:11
  • Browser loads resources after constructing whole DOM but JS blocks DOM construction.Even if modern browsers request images as soon as they're encountered in markup (for performance reasons) DOM construction is paused when a script tag is encountered i.e. script is executed and only then DOM is built (and rendered). – cyberskunk Feb 26 '15 at 11:34