简体   繁体   中英

Relative file path not working in JavaScript

I am trying to make pages load faster by including in-line css for above the fold code. This works for pages held in the root directory, but I have a problem with loading the rest of the CSS file at the end of the pages that are in sub folders (ie http://example.com/other/index.html ).

If the current file is in the root folder the following code works fine:

   <script>var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'css/a1tg2.css';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);</script>

but if the current file is in a sub folder the following code does not work:

 <script>var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = '../css/a1tg2.css';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);</script>

Also, if I try an absolute path it also does not work:

   <script>var cb = function() {
var l = document.createElement('link'); l.rel = 'stylesheet';
l.href = 'http://example.com/css/a1tg2.css';
var h = document.getElementsByTagName('head')[0]; h.parentNode.insertBefore(l, h);
};
var raf = requestAnimationFrame || mozRequestAnimationFrame ||
webkitRequestAnimationFrame || msRequestAnimationFrame;
if (raf) raf(cb);
else window.addEventListener('load', cb);</script>

The relative location of the file is correct because if I have the following line in the head of the document:

<link href="../css/a1tg2.css" rel="stylesheet" type="text/css">

It also works fine, but I don't want to use that as it slows down the rendering of the page. I am not proficient with JavaScript, just getting the code required from an on-line critical path CSS generator. Can anyone offer a solution please, as none of the similar questions on this site have a satisfactory answer.

check the link of the html file generated and use a path relative to that page. For example: If your directory structure is:

 - css
    - a1tg2.css
- pages
   - header.php
   - footer.php
- index.php

If you are including header.php inside index.php, the relative path of the css file in header.php should be css/a1tg2.css and not ../css/a1tg2.css

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM