JQuery attr function to replace image src not working in browsers except Chrome
Hi all, As per title, I believe there are a lot people who face this problem when want to dynamically update an image using JQuery. Once there is a requirement for this, the first thing come out in mind is the .attr() function provided by JQuery. The code roughly will be like this: $('#<image element id>').attr('src',<new image source>); Logically this should be done the job. However, after a test in several browsers, one will find out that this only working in Chrome. Internet Explorer, Firefox and Safari do not perform as expected. Why will this happen? It is due to cache issue. The solution for this issue is very simple. It is just needed to append a timestamp behind the new image source to trick the browser that the image is a new one for each time the function is triggered. It is as below: $('#<image element id>').attr('src', <new image source> ?' + new Date().getTime() ); * the part highlighted in yellow is ...