javascript - 浏览器在动态添加的基本 html 标记后加载 Assets 两次

标签 javascript jquery html offline-browsing

为了处理网站中的相对路径,我使用 <base> <head> 中添加的标签每一页。 通过文档中类似相对路径加载的所有资源都已正确获取和显示,但是浏览器(在我的试验中是 Chrome 和 Firefox)加载每个 Assets 两次,一次使用真实的相对路径(给出 404 错误)和一次第二次使用 <base>标签附加在它之前。

我用这个脚本在每个 html 文件中手动编写实现这样的标签:

<head>
    <script>
        /* Where am I? */
        here = window.location.href;
        hereIndex = here.indexOf('prd-ita'); //find path to main folder

        /* make substring from local root till prd-ita/ */
        newPathname = here.substring(0, hereIndex+10); //+8 to consdier also prd-ita/


        document.write('<base id="host" href="' +  newPathname  + '"/>');
    </script>

...
</head>

举例说明,我的文件夹结构是这样的:

  • 珠三 Angular
    • index.html
    • 文件夹1
      • file1.html
      • 图片.jpg
      • 子文件夹2
        • 文件2.html

无论加载哪个 html 文件,基本标记生成的 href 都是 file:///D:/myWebsite/prd-ita/在 file2.html 中,我加载了路径为 src="folder1/pic.jpg" 的资源.
从检查工具中,我看到进行了两次加载尝试:

  1. 错误的路径(真正的相对路径解释)file:///D:/myWebsite/prd-ita/folder1/subfolder2/folder1/pic.jpg
  2. 正确路径(附加基本标记)file:///D:/myWebsite/prd-ita/folder1/pic.jpg

在你问之前我不会使用 /开始我的相对路径,因为它被解释为文件所在的驱动器号,我需要主 prd-ita 文件夹的完整路径。我只想使用客户端代码(例如不使用 php)。

最佳答案

我遇到了同样的问题,对我有用的解决方案是在脚本元素上添加 defer 属性。不过,这可能并不理想,具体取决于您的应用。

来自 the Mozilla docs :

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.

关于javascript - 浏览器在动态添加的基本 html 标记后加载 Assets 两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30191624/

相关文章:

javascript - 如何在水平行中显示按钮?

javascript - PHP 表单 - 单击单选按钮提交表单

javascript - 在 typescript 中访问类属性

javascript - 更改方法时未过滤正确的日期

html - IE 9 渲染问题

Canvas 的 JavaScript 问题 - Chrome 中正常/Firefox 中错误

javascript - 将 "&lt;script src="的值直接分配给另一个元素

javascript - 通过表单发送电子邮件,无需刷新

c# - 用于 Web 应用程序的开源照片马赛克

javascript - 无法使用 datatable.js Ajax 添加行