I added the following code to my asp.net-mvc site.master page with the goal is making sure this image gets loaded upfront and cached (as I use it all over my site):
$(document).ready(function () {
var x = new Image();
x.src = "/content/images/ajax-loader.gif";
I am assuming this code would force a preload and cache of this ajax loading image but when i run a page that references this image, i still see this for a few seconds. Here is an example of a jqgrid loading div
which uses this code for loadtext:
$.jgrid = $.jgrid || {};
$.extend($.jgrid,{
defaults : {
recordtext: "View {0} - {1} of {2}",
emptyrecords: "No records to view",
loadtext: "Loading Data ...<img src='/Content/Images/ajax-loader.gif' />",
pgtext : "Page {0} of {1}"
},
before my actual ajax loading image shows like below:
Is there any suggestion for what could be causing this and how to ensure this image is loaded and cached prior to trying to use it? Is my solution actually redownloading the file each time?
What is the best recommendation here for how to achieve my goal?
Whenever you use an
img
element, the browser will request it from server. Using CSSbackground-image
, will request the image only once, and you can use it multiple times, without seeing that problem again.I think that the only correct way to cache the image is setting some
max-age
in the header of the server response (I mean something likeCache-Control: max-age=691200
or higher). You can load the GIF even from any other place in Internet/Intranet where you can more easy specify the caching attribute of the GIF file.If your site run on IIS7 or higher you can add the section
within
<system.webserver>
(see the link and here).Try utilizing data URIs
Since browsers may ignore relative image paths generated by Javascrip, I recommend You to use this:
And its style would be something like this:
Note that Configuring the Server cache is needed when you wanna avoid getting the same images in the next visits (not needed in current session).
To pre-loading the image, you should attach your image to the document.
But to make 100% sure the image is available before use, even before preload finish. you should use data-uri image.
There are a lot of data uri generator out there, http://dopiaza.org/tools/datauri/index.php for example.
Put this image in an hidden element at top of your master page.
You are loading this image in master page on document.ready(), which gets called on complete page load. And I feel there may be chances that your new page where this gif is being showed up is not fetched from the server already.
To check if image is being downloaded every time or not, use google chrome developer screen's Network tab.