angular.js - 用Angular的$http.get获取的png图片未能如愿缓存(预加载)
天蓬老师
天蓬老师 2017-05-15 16:51:10
0
2
695

具体调用如下,五张图片都预先ajax获取了,但之后还是重新远程获取了一遍:

正确的应该是这样(有“from cache”,时间0ms):

01~05五张图片的调用代码如下(其中第一个图片尝试改成了另一种方式,但仍然如旧):

    var req = {
        method: 'GET',
        url: '/images/donghua/01.png',
        headers: {
            'Accept':'image/png',
            'Content-Type': 'image/png'
        }
    }
    $http(req).success(..someFunction..);
    $http.get('/images/donghua/03.png').success(..someFunction..);
    $http.get('/images/donghua/04.png').success(..someFunction..);
    $http.get('/images/donghua/05.png').success(..someFunction..);
    $http.get('/images/donghua/02.png').success(..someFunction..); 

nodejs服务器端是这么写的:

var express = require('express');
var app = express();
//var fs = require('fs');

app.get('/', function(req, res){
//    fs.readFile('index.html', 'utf-8', function(err,data){
        res.sendFile('index.html',{root:__dirname});
//    });
});

app.get('/images/donghua/:img', function(req, res){
    console.log(__dirname + '/images/donghua/' + req.params.img);
    res.sendFile(req.params.img, {
        root : __dirname + '/images/donghua/'
    });
});

app.get('/angular/:ajs',function(req, res){
    res.sendFile(req.params.ajs, {
        root : __dirname + '/angular-1.3.14/'
    });
})

app.listen(8080);

http://stackoverflow.com/questions/26073183/read-remote-file-and-output-to-browser-work-with-text-and-html-dont-work-wit/26075653#26075653
不知道stackoverflow的这个问题和我遇到的有没有关系……

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
为情所困

When placed in img src, it will be retrieved according to the address of the image, and the previous preloading will not work

If you want to implement preloading, you can preload the image and convert it to base64 and put it in src

I don’t know if I understand your question correctly

迷茫

Your request should add caching parameters, the default is not caching:

$http.get(imgUrl, {cache : true})
        .success(function(data, state, header, config) {
        })
        .error(function(data, state, header, config) {
            console.log("load error!");
        });

Add cache : true to tell angular to cache requests to the $http cache

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template