We have set a public folder containing 50 small images of Portable Network Graphics format, basically icons of (45 x 45px) for a toolbar design.
Consider the following Node.js code used for setting public folder using express:
app.configure(function AppConfig() {
app.set('port', 8080);
app.use(express.bodyParser());
app.use(express.errorHandler());
app.use(express.cookieParser());
app.use(express.static(app.root + '/app/public')); // <== contains 50 icons in .png format
app.engine('html', require('hbs').__express);
app.set('views', app.root + '/views/html');
app.set('view engine', 'html');
});
Since first page is Sign-In page always, I want all the toolbar icon images to be cached on first page load itself at background, while user is entering Sign-In details.
While searching how to do it at background, I came across Image Sprite concept. But I require different solution to cache images which are not yet requested.
Could any one put some light on how to do this?
Update: I tried to use tag itself requesting for a single image (.png) which is Image Sprite of all 50 having Size: 0.76MB, now when I load Sign-In page it loads images and then user can see the UI. So the issue is I want it to show UI first and then load the images at background something like AJAX.
You can pre-load your image sprite by inserting it at the most bottom of your Sign-in page & making it invisible. While the browser is parsing and rendering your Sign-in page, it will encounter your image sprite and load it but will not display it. Because it's at the end of the page, it will not interfere with the UI and your users will see the UI first.
<html>
<body>
...
<div style="display:none">
<img src="sprite.png"/>
</div>
</body>
</html>
Or you can load it using JavaScript
$(function() { // when DOM is ready
$(window).load(function() { // when the page is fully loaded including graphics
$('body').append($('<div><img src="sprite.png"/></div>').hide());
});
});
Also, don't forget to instruct express to tell the browser that the sprite can be cached:
app.use(express.compress()); // optional
app.use(express.static(app.root + '/app/public', { maxAge: 86400000 /* 1d */ }));
Server can only serve content which is requested by user. Caching is done by browser to reduce the file transfers (required by the page) and improve performance.
For caching to happen, browser must request the files at least once. Thereafter it checks if the files are updated or not. If file has changed on server the cache is discarded, else it uses the cache. If you want to cache all the images, simply include them in your login page. After that, every request for the files will hit the cache. To know that your file is being cached in node check the logs.
//First access
GET /stylesheets/style.css 200 1270ms
//Thereafter from cache
GET /stylesheets/style.css 304 6ms
Don't worry about caching, let the browser handle it.
Related
I am trying to understand how to cache an Image url so that it does not need to be redownloaded.
I have taken a look at: https://docs.expo.io/versions/v19.0.0/guides/preloading-and-caching-assets.html
and have been using Image.prefetch like so:
const prefetchedImages = images.map(url => {
console.log('url', url) //this is correctly logging the url
return Image.prefetch(url)
});
Promise.all(prefetchedImages)
.then(() => {
this.setState({loaded:true})
})
This ultimately does set the state as true. I am then rendering my Images in a different component, but I make sure the component that is prefetching does not unmount. I load the url like so:
<Image source={{uri: myImageUrl}} style={{width:100, height:100}} />
When I load images into my grid view, only the local images appear right away, and the ones with URLs are white for a moment before rendering. When using cache:‘force-cache’ on iOS, the images are in fact loaded from cache and there is no lag. I thought I did not need to do that if I used prefetch.
Am I missing something here? I thought I can call my Image source as usual and the system will know how to grab the cached image for that url.
I do not think prefetch is quite as simple as just loading the image from cache just because it is in the cache, if that makes sense.
Check out this thread https://github.com/facebook/react-native/issues/2314 and this question React native Image prefetch.
If you want to save images and have them always available offline look at https://www.npmjs.com/package/react-native-preload-images.
If I call a resource in a webpage (e.g. a pixel from tracker.com at the beginning of body), and tracker.com is very slow to answer (e.g. >10s or even timeout), what are the consequences to my webpage load?
Will the other resources (script, images, css, etc) be displayed as usual?
If not, is asynchronous tag an option?
Loading resources, as you call it, will not delay the domready or document ready page event, however it will delay the load page event. The actual behaviour of page loading depends on browser - the browser should download the resources from different hosts in paralel. It will not affect the whole page rendering, unless you use images with unspecified width and height - in that case browser must re-render the page after receiving the image.
So when well designed, the only problem would be the delayed load event.
In case of very slow-loading resources you can avoid that by the use the "asynchrounous tag" - just handle the domready event and place new tags. E.g. in jquery use:
$(function () {
// this code will be run after dom ready event
});
I'm working on a website where the homepage has a rotating banner. When the page is loaded, an AJAX request is performed to retrieve the rest of the banners (each of which has a 960-pixel wide image). I toyed with the idea of loading the page normally with all the banner HTML loaded, but the target audience of the website are not always guaranteed to be on a blazing connection, and I wanted the homepage to load quickly. Plus, I didn't want conflicting H1 tags. The page in question is the landing page at http://www.gosihanoukville.com/
If you're on a slowish connection, the banners will load and start moving (rotating) before the background images are finished loading. I'm wondering if there is a way to detect if an image has fully downloaded before I have the script start moving the banners.
I'm not including code here, as it is best seen on the website mentioned above. The JS file used is 'landing.js'
Thanks for any help - this is driving me crazy.
I would normally do this:
var imagesToLoad = [];
var imagesLoaded = 0;
// Register this handler using whatever framework you like
var whenImageLoaded = function(){
if (++imagesLoaded == imagesToLoad.length){
// Start moving the banners.
}
}
This is probably going to get a resounding no, but I am wondering if it possible to have the URl change dynamically with using hashing, and without invoking a http request from the browser?
My client is keen on using AJAX for main navigation. This is fine, when the end user goes to the front page first, but when they want to use the deep linking, despite it working, it forces an extra load time as the page loads the front page, then invokes the AJAX from the hash.
UPDATE: Could it be possible, given that what I want to avoid is the page reload (the reason is that it looks bad) to stem the reload by catching the hash with PHP before the headers are sent, and redirecting before the page load. This way only one page loads, and the redirect is all but invisible to the user. Not sure how to do this, but seems like it is possible?
Yes, this is possible. I often do this to store state in the hash part of the URL. The result is that the page doesn't reload, but if the user does reload, they're taken to the right page.
Using this method, the URL will look like: "/index#page=home" or "/index#page=about"
You'll need to write a JavaScript function that handles navigation, and you'll need a containing div that gets rewritten with the contents fetched from AJAX.
Home
About
Questions
<div id="content"></div>
<script type="text/javascript">
function link(page) {
location.hash = "page="+page;
loadPage(page);
}
// NOTE: This is using MooTools. Use the AJAX method in whatever
// JavaScript framework you're using.
function loadPage(page) {
new Request.HTML({
url: "/ajax/"+page+".html",
onSuccess: function(tree, elements, html) {
document.id('content').setProperty('html', html);
}
}).get();
}
</script>
Now, you'll also need to have something that checks the hash on page load to load the right content initially. Again, this is using MooTools, but use whatever onLoad method your JavaScript framework provides.
<script type="text/javascript">
document.addEvent('domready', function() {
parts = location.hash.split('=');
loadPage(parts[1]);
}
</script>
Ok, the problem is that opening an AJAX link of the form http://example.com/#xyz results in a full page being downloaded to the browser, and then the AJAX-altered content is changed once the page has loaded and checked the hash part of its URL. The user has a diconcerting experience.
You can hugely improve this by making a page that just contains the static elements - menus, etc. - and a loading GIF in the content area. This page checks its URL upon loading and dynamically fetches the content specified by the hash part. The page can have any URL you want; we'll use http://example.com/a. Links to this page (http://example.com/a#xyz) now provide a good user experience for users with scripting enabled.
However, new users won't come to the site by fetching http://example.com/a; they'll fetch http://example.com. This is fine - serve the full page, including the home page content and links that don't require scripting to work (e.g., http://example.com/xyz). A script run on loading this page should alter the href of AJAXable links to their AJAX form (http://example.com/a#xyz); thus the first link a user clicks on will result in a full page load but subsequent ones won't.
The only remaining problem is is a no-script user gets sent an AJAX link. You can add a noscript block to the AJAX page that contains a message explaining the problem and provides a link back to the homepage; you could include instructions on how to enable scripting or even how to modify the link by removing a# and pressing enter.
It's not a great answer, but you can offer a different link in the page itself; e.g., if the address bar shows /#xyz you include a link to /xyz somewhere in the page. You could also add a link or button that uses script to bookmark the page, which would again use the non-AJAX form of the link.
I'm writing a web application that involves a continuous cycle of creating (and removing) a fair number of images on a webpage. Each image is dynamically generated by the server.
var img = document.createElement("img");
img.src = "http://mydomain.com/myImageServer?param=blah";
In certain cases, some of these images outlive their usefulness before they've finished downloading. At that point, I remove them from the DOM.
The problem is that the browser continues to download those images even after they've been removed from the DOM. That creates a bottleneck, since I have new images waiting to be downloaded, but they have to wait for the old unneeded images to finish downloading first.
I would like to abort those unneeded image downloads. The obvious solution seems to be to request the binary image data via AJAX (since AJAX requests can be aborted), and set the img.src once the download is complete:
// Code sample uses jQuery, but jQuery is not a necessity
var img = document.createElement("img");
var xhr = $.ajax({
url: "http://mydomain.com/myImageServer?param=blah",
context: img,
success: ImageLoadedCallback
});
function ImageLoadedCallback(data)
{
this.src = data;
}
function DoSomethingElse()
{
if (condition)
xhr.abort();
}
But the problem is that this line does not work the way I had hoped:
this.src = data;
I've searched high and low. Is there no way to set an image source to binary image data sent via AJAX?
You would have to base64-encode the data into a data: URI to achieve that. But it wouldn't work in IE6-7, and there are limitations on how much data you can put in there, especially on IE8. It might be worth doing as an optimisation for browsers where it's supported, but I wouldn't rely on it.
Another possible approach is to use the XMLHttpRequest to preload the image, then just discard the response and set the src of a new Image to point to the same address. The image should be loaded from the browser's cache. However, in the case where you're generating the images dynamically you would need to pay some attention to your caching headers to ensure the response is cachable.
Try e.g.
this.src="data:image/png;base64,XXX"
...where XXX is your binary data, base64-encoded. Adjust the content-type if necessary. I wouldn't be optimistic about wide browser support for this, though.
You should be able to use data URIs, similar to the solution I identified in an earlier question. Note that this will not work with older browsers.