Reputation: 103428
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?
Upvotes: 1
Views: 1886
Reputation: 1384
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.
Upvotes: 1
Reputation: 1772
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>
Upvotes: 0