snipt

Ctrl+h for KB shortcuts

JavaScript

Check if an image is loaded with jQuery

1
2
3
4
5
6
7
8
9
//Here’s a snippet I often use when working with images, 
//as it is the best way to know if an image is loaded or not.

var imgsrc = 'img/image1.png';
$('<img/>').load(function () {
    alert('image loaded');
}).error(function () {
    alert('error loading image');
}).attr('src', imgsrc);
https://snipt.net/embed/d79b1bbe9b1adb4c475f3babb3ecb6fa/
/raw/d79b1bbe9b1adb4c475f3babb3ecb6fa/
d79b1bbe9b1adb4c475f3babb3ecb6fa
js
JavaScript
10
2019-06-15T17:31:11
True
False
False
Feb 02, 2014 at 06:06 AM
/api/public/snipt/110252/
check-if-an-image-is-loaded-with-jquery
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a> <a href="#L-7">7</a> <a href="#L-8">8</a> <a href="#L-9">9</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="c1">//Here’s a snippet I often use when working with images, </span> </span><span id="L-2"><a name="L-2"></a><span class="c1">//as it is the best way to know if an image is loaded or not.</span> </span><span id="L-3"><a name="L-3"></a> </span><span id="L-4"><a name="L-4"></a><span class="kd">var</span> <span class="nx">imgsrc</span> <span class="o">=</span> <span class="s1">&#39;img/image1.png&#39;</span><span class="p">;</span> </span><span id="L-5"><a name="L-5"></a><span class="nx">$</span><span class="p">(</span><span class="s1">&#39;&lt;img/&gt;&#39;</span><span class="p">).</span><span class="nx">load</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> </span><span id="L-6"><a name="L-6"></a> <span class="nx">alert</span><span class="p">(</span><span class="s1">&#39;image loaded&#39;</span><span class="p">);</span> </span><span id="L-7"><a name="L-7"></a><span class="p">}).</span><span class="nx">error</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span> </span><span id="L-8"><a name="L-8"></a> <span class="nx">alert</span><span class="p">(</span><span class="s1">&#39;error loading image&#39;</span><span class="p">);</span> </span><span id="L-9"><a name="L-9"></a><span class="p">}).</span><span class="nx">attr</span><span class="p">(</span><span class="s1">&#39;src&#39;</span><span class="p">,</span> <span class="nx">imgsrc</span><span class="p">);</span> </span></pre></div> </td></tr></table>
image, javascript, jquery, loading