javascript - 使用 AngularJS 从 Unsplash 预加载随机图像

标签 javascript angularjs angularjs-directive

我正在尝试预加载从 Unsplash URL 调用的图像:

https://source.unsplash.com/random.

如您所见,此 URL 返回随机图像的 URL。我正在尝试预加载返回的图像,但无法获取所选图像的返回 URL。

var image = new Image();
    image.src = 'https://source.unsplash.com/random';
    image.onload = function(){
      element.css('background', 'url('+ image.src + ') no-repeat center center fixed');
    };

虽然这在 Chrome 上有效,但更改背景图像在加载时不会出现空白屏幕,但在 Safari 上则不起作用。

我怀疑 Safari URL 将在成功事件时再次调用另一张图像,并且会在加载新图像时显示空白屏幕。

我正在使用 AngularJS,当我调用随机 URL 时,有什么方法可以获取图像的返回 URL?

谢谢!

最佳答案

你可以这样做:

var image = new Image();
image.src = "https://source.unsplash.com/random";
$("#somewhere-to-append-the-image").hide(0).append(image);
image.onload = function() {

    var img = $("#somewhere-to-append-the-image > img");

    // work with the img here
    $("#somewhere-to-append-the-image").fadeIn(100);
}

遗憾的是,您仍然无法在 img.attr("src") 中获得图像的真实 URL,也无法在将来以任何方式再次引用同一图像。

这是因为它是 302 重定向,而客户端脚本无法拦截 302 重定向,它会自动解析,您对此无能为力。不过,您可以在服务器端读取 302 header ,因此这是获取真实 URL 的唯一解决方法。因此,您必须向服务器发出 ajax 请求,让它解析 302,并使用正确的 URL 进行响应。然后我编写的上述代码仍然可以与解析的 url 一起用于预加载目的。

我很确定 Unsplash 是故意这样设置的,因为我在他们的网站上读到过:

Hotlinking Unlike most APIs, we prefer for the image URLs returned by the API to be directly used or embedded in your applications (generally referred to as hotlinking). By using our CDN and embedding the photo URLs in your application, we can better track photo views and pass those stats on to the photographer, providing them with context for how popular their photo is and how it’s being used.

https://unsplash.com/documentation

但是我确实认为有一个有效的用例可以加载随机图像,并保留 URL 以供以后重复使用,而无需通过他们的 JSON API,所以这就是为什么我建议在服务器上处理 302通过中间 Ajax 调用。

为了更进一步,我将违背 Unsplash 的偏好,将他们的图像缓存在我自己的服务器上。如果您手动提取他们的图像,那么您绝对会这样做。他们随时可能会停止服务,您的后台也会停止工作。诸如此类的小事,只是一点保证而已。也许您可以两者都做,并优先使用他们的 CDN,但如果他们的服务器出现问题,最好有一个后备方案。

不过,请仔细阅读他们的条款并做出自己的决定。

关于javascript - 使用 AngularJS 从 Unsplash 预加载随机图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34528277/

相关文章:

javascript - javascript 模板字符串中的默认值

javascript - GruntJS 可配置首次运行

javascript - Require.config 抛出错误 : EXPECTING 'STRING' in chrome

javascript - 随机化功能的绑定(bind)/分离/append

javascript - 使用 Angular 从 ng-repeat 添加和删除项目,简单的购物车实现

angularjs - 谷歌地图 fitBounds 不工作

javascript - AngularJs 将 HTML 中每个 ng-repeat 的实例传递给指令

javascript - 使用 Angular.js 移动到另一个页面时,表单内的指令不起作用

javascript onclick 不工作?

javascript - BLOB 对象不可见