“Bad value for attribute src on element img: Must be non-empty”, for dynamically generated img src

前端 未结 2 1324
滥情空心
滥情空心 2020-12-19 13:26

I have a web site with an image slider. I keep the some of the image tags empty as the images load on when slide comes into view for faster page load. The image tags defined

2条回答
  •  情话喂你
    2020-12-19 13:47

    Set the image src attribute to #:

    Thumbnail
    

    The HTML passes the W3C validator just fine, and modern browsers know not to try to load the non-existent image.*

    For contrast, using a src value that references a non-existent file results in an unnecessary HTTP request and an error:

    Thumbnail
    

    Failed to load resource: The requested URL was not found on this server.

    *Note: I've read conflicting information on how browsers handle the #. If anyone has definitive information, please add a comment.

    Also see related answer by sideshowbarker about the action attribute:
    https://stackoverflow.com/a/32491636

    Update: December 2019

    It seems the src="#" trick used to be a decent workaround but not anymore. What I do now is create a Gulp build task to post-process src="#" to use an inline data URL of a tiny invisible one pixel SVG.

    The essential gulpfile.js bits look like:

    const onePixelSvg = '';
    const placeholderSvg = `"data:image/svg+xml;base64,${Buffer.from(onePixelSvg).toString('base64')}"`;
    
    const task = {
       buildHtml() {
          return gulp.src('src/html/**/*.html')
             .pipe(replace('src="#"', 'src=' + placeholderSvg))
             .pipe(gulp.dest('build'));
          }
       };
    gulp.task('build-html', task.buildHtml);
    

    The advantage of using a build task is that 1) the source remains uncluttered, 2) the HTML always validates, and 3) the inline data URL prevents the browser from making an unnecessary and invalid network request.

提交回复
热议问题