简体   繁体   中英

how can js(jquery) run before image is loaded

I want to change image url when the images are not loaded in html DOM. (before browser loads image)

Can js do this?

demo code:

...
<body>
   <img src="old src"> <!-- this **HTML** is loaded from a database and i want to change this src using javascript-->
</body>
....

I tried

$(function(){$(img).attr('src','new src');}); //it is can work ,but the brower will load old image first. then the js will run.

Beacause the HTML is loaded from a database, I have no idea how to operate html string in server code(java). so i want use js to change image src.

EDIT:

for example:

old src = "old domain/test.jpg" i want to change it to "right domian2(CDN)/test_width_height.jpg"

the old src is not in server, so the brower will get 404 error from server first. when the src change to new src, then brower will reload image from new src, then the correct image will display.

i do not want the borwer 404 error first, i just want the browser to load the right image from the right address.

If you have any problem in loading the image, you can alternatively set the other image in onError

<img src="old domain/test.jpg" alt="Not Available"
 onError="this.src='right domian2(CDN)/test_width_height.jpg';" />

You can use the image complete property to determine wheather the image is loaded or not . If not you can modify the src of the img tag as required.

Please have look at the below url ,

http://www.w3schools.com/jsref/prop_img_complete.asp

Hope this helps

In the beginning do not add any url to the image tag. add them at certain condition like on pageload as

// define the function that assign the image url
function assignImageSrc(){ 
    $('#imageID').prop('src','add your url here');
}

call it as

<form onload="assignImageSrc()" >
//
</form>

Hope it helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM