开发者

Prevent put absolute paths in javascript for css files

I am using javascript and somethimes a cretain js file need specific css file made for it. I want to prevent put absolute paths of the css files in javascript. I even want to put the js file in the same folder of the css file. But the path of the js file is calculated from the file that executes it.

How can I connect开发者_运维技巧 between this js file and the css file?


There is no perfect solution to this.

One of the solutions that come to mind is to analyze (using DOM) the script tags on page to find out the path that was used to load script itself, then calculate path relative to this.

Other solution is to use js combiner and css combiner and just always load all js and css needed for site.


But the path of the js file is calculated from the file that executes it

This is not always true. Just start the path with a forward slash and it will be relative to your root web directory e.g.

<link type="text/css" rel="stylesheet" href="/path/to/style.css" />


You can declare one global variable holding the "relative" path than use it whenever you need to specify file path. Example:

<script type="text/javascript">
var _relPath = "MyFolder/CSS";

...

function SomeFunc() {
   var cssFileName = _relPath + "/myfile.css"; //instead of MyFolder/CSS/myfile.css
}

...
</script>

This way it's easier to change.

If you have server side language in use e.g. ASP.NET, classic ASP, PHP - you can output the relative path of the current page let us know if relevant.


It would be simpler just to define the needed CSS within the JavaScript file, if you absolutely need to link the CSS and JavaScript together. You can make a HTML page use CSS files dynamically from JavaScript by adding new link tags, but to my best knowledge, there is no way to specify the paths relative to the JavaScript file.

However, one thing you could do is this. First have each HTML file specify the script root path relative to that file, like:

<script type="text/javascript">
    var jsPath = "relative_to_this_file/styles_and_scripts/"
</script>
<script type="text/javascript"
    src="relative_to_this_file/styles_and_scripts/styler.js">
</script>

and having the styler.js code do this:

var myStylePath = jsPath + "myStyle.css"
// add link tag for the CSS to HTML here using myStylePath

You could also generate absolute paths in JavaScript or in code that is serving the JavaScript dynamically in a similar fashion. If the root part of the absolute path changes, you only need to adjust a single line of code accordingly.

Alternatively, you could also consider a different strategy: link the CSS files statically from your HTML pages, and use classes in your CSS selectors (.myClass { float: left; } ). Then you can easily use JavaScript to add new classes to the HTML tags you want to style.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜