Skip to content

Instantly share code, notes, and snippets.

@atsu666
Last active October 2, 2017 10:42
Show Gist options
  • Save atsu666/39107fc7afc67541abec346ae69cd89a to your computer and use it in GitHub Desktop.
Save atsu666/39107fc7afc67541abec346ae69cd89a to your computer and use it in GitHub Desktop.
画像のフォールバック
module.exports = (selector, fallbackImageUrl) => {
[].forEach.call(document.querySelectorAll(selector), image => {
const imageObj = new Image();
imageObj.onerror = (() => {
imageObj.onerror = null;
image.src = fallbackImageUrl;
});
imageObj.src = image.src;
});
}
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).ImgFallback=e()}}(function(){return function e(n,r,o){function t(i,u){if(!r[i]){if(!n[i]){var c="function"==typeof require&&require;if(!u&&c)return c(i,!0);if(f)return f(i,!0);var l=new Error("Cannot find module '"+i+"'");throw l.code="MODULE_NOT_FOUND",l}var d=r[i]={exports:{}};n[i][0].call(d.exports,function(e){var r=n[i][1][e];return t(r||e)},d,d.exports,e,n,r,o)}return r[i].exports}for(var f="function"==typeof require&&require,i=0;i<o.length;i++)t(o[i]);return t}({1:[function(e,n,r){"use strict";n.exports=function(e,n){[].forEach.call(document.querySelectorAll(e),function(e){var r=new Image;r.onerror=function(){r.onerror=null,e.src=n},r.src=e.src})}},{}]},{},[1])(1)});
<!DOCTYPE html>
<html lang="ja">
<head>
<script src="img-fallback.min.js"></script>
<script>
window.addEventListener('DOMContentLoaded', function() {
/**
* 第1引数に画像につけるclass名を
* 第2引数に代替画像のパスを指定してください。
*/
ImgFallback('.js-img-fallback', '/path/to/noimage.png');
});
</script>
</head>
<body>
<h1>Sample</h1>
<img src="http://example.com/sample.png" class="js-img-fallback">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment