Is it possible to run javascript before images begin loading?

后端 未结 3 1308
轻奢々
轻奢々 2021-01-11 12:02

I\'d like to change the src attribute of images before they are requested by the browser, the aim being to reduce the size of the images using a PHP script like Timthumb. Us

3条回答
  •  时光取名叫无心
    2021-01-11 12:34

    You cannot change the DOM of the page before the DOM has been loaded. And, once the DOM has been loaded, the browser has already started requesting images. So, you cannot change tags before they start loading their images.

    What you could do is change the source of the page to not have any of the images you want to change in the source of the page and then use javascript to dynamically insert the desired images after the page has been loaded. This way the browser will never request the wrong images.

    Or, you could change the tags to not have a .src property at all and with your Javascript you would add the .src property. An tag with no .src property will not display until you provide it with a .src property.

    If you're worried about the wrong images flashing as they are loaded before you change them to the correct images, you can use CSS in a stylesheet to hide the images initially and then after you change the img.src to the correct value and that new .src value has loaded, you can make them visible.

    If you can't change the source of the page, then all you can do is hide the images initially (using CSS) until the correct .src has been set on them and that new .src value has been loaded.

提交回复
热议问题