Including Javascript on web pages

Can anyone recommend a better and simpler way to include multiple Javascript files in a webpage (in PHP)?

I have a website that uses jQuery and all up to 10 plugins on any single page. I'm not entirely sure about the best way to use all of these files to make life simple for me as a developer and to ensure that they serve the user best.

Ideally, I thought the easiest way I could create a PHP handler file that I could use to call the plugins I request for each page, and then output the javascript that used document.write () to "include" each plugin JS on the page, for example:

<script src="handler.php?jquery,plugin1,plugin2,plugin3,plugin4"></script>

      

which can then output Javascript with multiple document.write () for each individual plugin.

I am convinced that this can lead to browser caching issues, as some browsers ignore caching of chain items.

Is this okay to do, or is there an easier method that may be missing?

0


a source to share


5 answers


Joely,



Browsers have no problem caching url with question marks. It is probably best not to include a js file, which in turn includes another js file. If you're already writing a script that manages all the js files that need to be included, why not output those script tags right there?

+1


a source


you might be interested in the Google AJAX API , i.e.



google.load("jquery", "1.3.2");
google.load("jqueryui", "1.7.1");
google.load("prototype", "1.6.0.3");

      

+2


a source


Why not just include each of the files separately with their own tag <script>

? Then everything is cached individually and all is well. There will be many HTTP requests to load the first page. Dynamically creating an "include file" each time probably won't be better for performance.

Does the combination of scripts have a significant impact? If you really want to reduce HTTP requests and you always include the same 10 files, just concatenate them all together into one long file.

+1


a source


If you're really not inclined to include files separately, you could probably write a php function to generate script tags given a list of plugin names.

0


a source


function loadScripts(funcs){
    //funcs being an array list of paths to the scripts.
    var temp;

    //lets get a reference to the head tag
    var h = document.getElementsByTagName('head')[0];
    for(var i=0; i < funcs.length; i++){
        temp = document.createElement('script');
        temp.setAttribute('src', funcs[i]);
        temp.setAttribute('type', 'text/javascript');
        h.appendChild(temp);
    }
}

      

0


a source







All Articles