javascript - 如果在指定路径中找不到文件,他们是否可以在页面加载时更改 css 和 js 的源文件路径

标签 javascript jquery html css

假设缩小的 css/js 文件存储在单独的文件夹中,那么如果找不到特定的缩小文件,那么我们如何使用 js 或 jquery 或任何其他方式更改非缩小文件的 src/href 路径?例如:

<link href="path/to/minifiedfile.css">
.
.
.
<script scr="path/to/minifiedfile.js">
.
.
.
this files are not found, is their any way to replace those paths to nonminified files with jquery or javascript

i have tried with js onerror but need to mention onerror function call in all link and scripts tag so any other way using jquery?

    <html>
        <head>
        <title></title>
        <link href="path/to/minified.css" onerror="this.href=myfunction(this.href);">
        <link href="path/to/minified.css" onerror="this.href=myfunction(this.href);">
        <link href="path/to/minified.css" onerror="this.href=myfunction(this.href);">
        .
        .
        .
        <script scr="path/to/minified.js" onerror="this.src=myfunction(this.src);">
        <script scr="path/to/minified.js" onerror="this.src=myfunction(this.src);">
        <script scr="path/to/minified.js" onerror="this.src=myfunction(this.src);">
        <script scr="path/to/minified.js" onerror="this.src=myfunction(this.src);">
        .
        .
        .
        <script>
            function myfunction(link) {
            var nonminifiedpath = link.replace('/minified', '');
            return nonminifiedpath;
        }
        </script>
        </head>
    <body>
    </body>
    </html>

onerror="this.href=myfunction(this.href); 这需要在每个链接标签中使用,所以还有其他方式吗?

最佳答案

为纯 JavaScript 在 querySelectorAll 上使用循环:

document.querySelectorAll("script").forEach(e => e.onerror = myfunction(e.src));
document.querySelectorAll("link").forEach(e => e.onerror = myfunction(e.href));

jQuery 版本:

$("script").each((_, e) => e.error(() => myfunction(e.src)));
$("link").each((_, e) => e.error(() => myfunction(e.href)));

关于javascript - 如果在指定路径中找不到文件,他们是否可以在页面加载时更改 css 和 js 的源文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57414418/

相关文章:

jquery - 使用 jQuery 浮点图绘制曲线

Javascript 和 JQuery 奇怪的问题或者我做错了什么?

asp.net - html文本框的最大长度是多少

javascript - 防止 .lastChild 返回回车?

javascript - Web 开发人员如何在团队中工作

javascript - jquery xml 存在

html - 格式化双列表

javascript - 相对于窗口高度操纵 div 高度

javascript - 整个数组的 IndexOf 和警报名称

javascript - 如何防止我们网站的图像和内容被盗?