Relative paths of images in JavaScript

前端 未结 3 2091
我在风中等你
我在风中等你 2021-02-18 23:11

I have a javascript module which creates a div with a picture of a close button (\"X\"). This div and javascript are placed in many places on my site.

Relative path solu

3条回答
  •  鱼传尺愫
    2021-02-18 23:35

    Mutable paths (test/staging/production domains) is always a problem in javascript, the best option is to include the root path of your application/website in the HTML. The obvious place to do this is in your template layer. For example:

    
    
    

    And grab it with javascript for usage in your scripts.

    var rootContext = document.body.getAttribute("data-root");
    

    Note, you can only do this when the DOM is ready (or when document.body is available, differs cross browser) ;)

    An alternative and in my view less pretty option is to simply render javascript.

    
    

    At least with the 'data-root' technique, you can store the value wherever you like and avoid a global definition.

    So in your code where you reference an image, you can do the following:

    img.src = rootContext + "/media/js/close.gif";
    

    Or create a nice helper method:

     // lets use a namespace to avoid globals.
     var myApp = {
         // still need to set this when DOM/body is ready
         rootContext: document.body.getAttribute("data-root"),
         getContext: function( src ) {
             return this.rootContext + src;
         }
     }
    
    img.src = myApp.getContext( "/media/js/close.gif" );
    

    In the helper method, you can also write some code to ensure proper uses of / and whatnot.

提交回复
热议问题