How to check the availability of a resource using JavaScript?

前端 未结 2 1517
半阙折子戏
半阙折子戏 2020-12-18 05:50

If I have a URL to a video file, how can I detect if the resource pointed by the URL is valid and exists before it can be displayed? I\'ve seen some answers suggesting AJAX,

相关标签:
2条回答
  • 2020-12-18 06:20

    You don't really need ajax, just create a video element, and see if it can load the source

    var video = document.createElement('video');
    
    video.onload = function() {
        alert('success, it exsist');
        // show video element
    }
    
    video.onerror = function() {
        alert('error, couldn\'t load');
        // don't show video element
    }
    
    video.src = 'http://www.example.com/video.mp4';
    

    Different browsers play different formats, to check if the file can be played in the current browser, you can use the canplaythrough event

    video.oncanplaythrough = function() {
        alert("This file can be played in the current browser");
    };
    

    if the file is on the same domain, and ports and protocol match, you can use ajax to do a HEAD request and see if the resource exists, but that won't work cross-domain

    var http = new XMLHttpRequest();
    http.open('HEAD', '/folder/video.mp4');
    
    http.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            if (this.status != 404) {
              // resource exists
            }
        }
    };
    
    http.send();
    
    0 讨论(0)
  • 2020-12-18 06:39

    You can send a HEAD request. HEAD requests send back only the HTTP headers, so if you get a status of 200 or 304 it means the resource exists, if you get a 404 it means the resource doesn't exist.

    0 讨论(0)
提交回复
热议问题