Get script path

前端 未结 13 1583
青春惊慌失措
青春惊慌失措 2020-11-30 01:21

In CSS, any image path is relative to the CSS file location.

f.ex if I put the CSS file in /media/css/mystyles.css and use something like



        
13条回答
  •  -上瘾入骨i
    2020-11-30 01:51

    As other posters mentioned you need to compute your base url for the script first, you can the script below to find it.

    // find the base path of a script
    var settings = {};
    settings.basePath = null;
    
    if (!settings.basePath) {
      (function (name) {
        var scripts = document.getElementsByTagName('script');
    
        for (var i = scripts.length - 1; i >= 0; --i) {
          var src = scripts[i].src;
          var l = src.length;
          var length = name.length;
          if (src.substr(l - length) == name) {
            // set a global propery here
            settings.basePath = src.substr(0, l - length);
    
          }
        }
      })('myfile.js');
    }
    
    log(settings.basePath);
    

提交回复
热议问题