relative path of a file in js
Permalink 3 users found helpfulI'm creating a theme which has a js file. I've included the file in header. Now the problem is that, it calls different css files on some specific condition. My problem is that I cannot point the css path correctly as js file won't allow me to add getThemepath function.
Currently I've added the relative path hard-coded, but its not the best option for a theme. Is there any suitable way to do that?
BTW here is my code:
window._config = { preset: 'standard', prefix: '/path/to/theme/css/style', resetCSS: true, breakpoints: { '1000px': { grid: { gutters: 25 } } } };
I need to set the path automatically. I was thinking to add the javascript on theme load. Is there any way to do that. If there is no way then I have to put the code in header as a open script.
Rony
<script> var themePath = "<?php echo $this->getThemePath(); ?>"; </script>
Then use it like this:
window._config = { preset: 'standard', prefix: themePath, resetCSS: true, breakpoints: { '1000px': { grid: { gutters: 25 } } } };
The JavaScript variable is available to other .js files, but as the PHP runs first, it can set the theme path before the JavaScript runs.
Rony
<script type="text/javascript" src="http://www.myjsdomain.com.au/myscript.php?folderPath=my/folder/path"></script>
Then in the php file, change the code to use PHP to output the JavaScript:
<? $folderPath = $_GET["folderPath"]; if (empty($folderPath)){ $folderPath = "/default/folder/path/here"; } echo "window._config = {"; echo " preset: 'standard',"; echo " prefix: '".$folderPath."',"; echo " resetCSS: true,"; echo " breakpoints: {"; echo " '1000px': {"; echo " grid: {"; echo " gutters: 25"; echo " }"; echo " }";
Rony
- Change it to read a data attribute and just write the data attribute from the theme header.
OR
- Change it to read a javascript constant, and set the constant from the header.
OR
- Change it to a callable function, and call the function with a parameter from some code in ready handler in the theme header or footer.
All are simple solutions that do not involve the overhead of streaming a JavaScript file from php.
A trick for passing any c5 derived info is to add it to a data attribute of a dom element, then read that attribute from the script.