Skip to content

Instantly share code, notes, and snippets.

@azproduction
Forked from 140bytes/LICENSE.txt
Created January 17, 2012 09:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azproduction/1625781 to your computer and use it in GitHub Desktop.
Save azproduction/1625781 to your computer and use it in GitHub Desktop.
Tiny image loader
function(s,l){
with(new Image) // my lovely ugly hack
onload=onerror=function(){
l(this) // pass image to callback
},
src=s // set src
}
// shorter one with `this` binding to Image instance in callback by @p01
// function(s,l){with(new Image)onload=onerror=l,src=s}
function(s,l){with(new Image)onload=onerror=function(){l(this)},src=s}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Mikhail Davydov <azazel.private@gmail.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "image",
"description": "Tiny image loader",
"keywords": [
"image",
"preloader",
"loader"
]
}
<!DOCTYPE html>
<title>Tiny image loader</title>
<div>Expected value: <b>width 16px</b></div>
<div>Actual value: <b id="ret">loading...</b></div>
<script>
var image = function(s,l){with(new Image)onload=onerror=function(){l(this)},src=s};
image('http://yandex.ru/favicon.ico', function (img) {
document.getElementById( "ret" ).innerHTML = 'width ' + img.width + 'px'
})
</script>
@p01
Copy link

p01 commented Jan 17, 2012

Save 18 bytes:

var image = function(s,l){with(new Image)onload=onerror=l,src=s}

image('http://yandex.ru/favicon.ico', function() {
document.getElementById( "ret" ).innerHTML = 'width ' + this.width  + 'px'
  })

@azproduction
Copy link
Author

@p01 I prefer not to change "this" in callbacks. Сonsidered this option, but decided not to touch "this". I'll put yours nearby.

@jed
Copy link

jed commented Jan 20, 2012

since you've got a ton of space here, you should consider using the node-style (err, data) signature for your callback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment