Why the script works only after reboot?

Help to understand, there is a script output images brickwork - but it only works after reloading the page, in all browsers I tried.

Here is the code .
July 8th 19 at 12:25
2 answers
July 8th 19 at 12:27
try to wrap in the document ready
July 8th 19 at 12:29
It seems to me that before the start of the script should be fully loaded all the photos. Ie first is full download photos, and then start the script. And the fact that everything works after a reboot - just the second time, the browser "pulls" images from the cache. If the picture is not loaded or not fully loaded, the script can't determine the image size.

Find more questions by tags JavaScriptjQuery