Get script path

前端 未结 13 1598
青春惊慌失措
青春惊慌失措 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条回答
  •  抹茶落季
    2020-11-30 01:47

    One line "Pathfinder", when you know your script file name (here include.js):

    // Script file name
    var file = 'include.js';
    
    // jQuery version
    var path = (src = jQuery('script[src$="' + file + '"]').attr('src')).substring(0, src.lastIndexOf("/") + 1);
    // jQuery with error handling
    var path = (src = jQuery('script[src$="' + file + '"]').attr('src') ? src : 'Path/Not/Found/').substring(0, src.lastIndexOf("/") + 1);
    
    // Plain JS version
    var path = (src = document.querySelector('script[src$="' + file + '"]').src).substring(0, src.lastIndexOf("/") + 1);
    // Plain JS with error handling
    var path = (src = (script = document.querySelector('script[src$="' + file + '"]')) ? script.src : 'Path/Not/Found/').substring(0, src.lastIndexOf("/") + 1);
    

提交回复
热议问题