0

I'm trying to write some custom JS codes to load other js files in joomla website. Here are the codes:

var j = jQuery.noConflict();

function loadJS(){
    var i,l = arguments.length;
    for (i=0;i<l;i++){
        var t = document.createElement('script');
        t.src = arguments[i];
        document.body.appendChild(t);
    }
}

j(document).ready(function(){
     loadJS('1.js','2.js','3.js');
})

The above codes are put in a ready.js file in joomla_root/customJS, 1.js, 2.js, 3.js are also in the same folder.

But the loadings of these 3 files all return 404 error.

With SEF enabled, The URL of the page loading them is localhost/index.php/pages/blog(here pages and blog are not actual folders but menu items), and the page is trying to load localhost/index.php/pages/1.js etc.

I can use relative path like loadJS('../../customJS/1.js') to overcome this, but it is not reliable. If menu item blog has a submenu, then on that page the browser will try to load localhost/index.php/1.js and return a 404 error.

So how to deal with this issue?

shenkwen
  • 3,536
  • 5
  • 45
  • 85

1 Answers1

0

I can see two possible solutions.

1) The first is to move all the JS code from "ready.js" into a PHP file so that you can insert "" before any script name. Basically the JS is dynamically generated with the full site root URL.

2) The second is similar, but only set a JS variable. I.e. you change the file where you invoke the ready.js like this:

<script>var joomla_site_root_url = <?php echo JURI::root() ?></script>
<script src="/ready.js"></script>

and then in your loadJS file

t.src = joomla_site_root_url + "/" + arguments[i];
Francesco Abeni
  • 4,190
  • 1
  • 19
  • 30