Small graphic returns

    Holivars about where to store pictures - in the database or in the file system - a thing not rare even for Habr. In general, there is no single-valued approach and cannot be, but if you look at the situation from the perspective of optimizing the delivery of content, then a reasonable compromise becomes a little more obvious, in my opinion.

    It is clear that storing large pictures in the database makes no sense. There are many reasons for this, and all of them have long been known to everyone, we are not considering FileStream yet. However, the task often arises of giving out a large amount of any trifle from one page - for example, avatars on blogs or social networks, thumbnails, news previews in feeds, etc., i.e. relatively light graphics, but in commercial quantities. The trouble is that the return of each such picture creates a separate connection to the server, as a result, loading one page generates several dozen requests for the return of any small thing, the total volume of which on the page can not exceed hundreds of kilobytes. For current channels, this is nothing, but a bunch of server requests when rendering a page is bad.

    Quite interesting is the solution, in which all this trifle pot-bellied will be given in one stream. Thus, we reduce the number of requests to the server by an order of magnitude, which means we increase the site’s resistance to DDoS attacks. As a pleasant bonus - the prospect of pumping usability: all images will appear on the page immediately (without the effect of "loading"), at the same time and without "holes". A short pause before their appearance does not count, subjectively, such a load looks "faster".

    It looks like this scheme: placeholders with IDs corresponding to the pictures in the database are placed in the text of the HTML file. Javascript “runs through” the placeholders and generates an XMLHTTP request string, in response to which the server returns an array of base64-encoded strings, which again the javascript spreads over the src of the respective placeholders.

    As a result, instead of receiving a couple of dozens of individual pictures weighing 2-5 kB, we get a JSON string of 50-100 kB in a single asynchronous request. That is, a) AFTER the main text content is loaded and rendered, and b) much faster due to the features of streaming text data.

    Working example (avatars are torn from the network).

    The code can be found in the source of the page. The servlet in PHP (works with SQLite) looks like this:

    What do you say, a completely stupid idea? Or did I invent a bicycle?

    Also popular now: