js判断url是否可用
问题
需要判断url是否可用,再去执行其他操作,代码如下:
const loadScript = (url) => {
return new Promise((resolve, reject) => {
const script = document.createElement('script')
script.onload = () => resolve(true)
script.onerror = () => resolve(false)
script.src = url
const head = document.head || document.getElementsByTagName('head')[0];
(document.body || head).appendChild(script)
})
}
const checkUrl = async() => {
const url = 'xxxx';
const flag = await loadScript(url)
if (flag) {
// do something...
}
}
上边方法在chrome浏览器可能会遇到报错 (失败)net::ERR_BLOCKED_BY_ORB
可使用下边代码判断url是否可用
const isUrlAvailable = (url) => {
return fetch(url, { method: 'GET', mode: 'no-cors' })
.then(response => {
console.log('response.ok', response.ok)
return true
})
.catch(error => {
console.error('URL 检查失败:', error);
return false;
});
}
const checkUrl = async() => {
const url = 'xxxx';
const flag = await isUrlAvailable(url)
if (flag) {
// do something...
}
}