3

What is the difference between loading javascript code direct from .js file or through .php like the following example :

<script type="text/javascript" src="myscript.php?id=1"></script>

The $_GET['id'] will tell the php to load script id = 1 (script1.js)

OR

<script type="text/javascript" src="script1.js"></script>

what is the fastest / efficient / safe way between those two method above

Thanks in advance.

1
  • 3
    What do you mean by "difference"? There's no difference at all from the browsers' perspective. Commented May 27, 2011 at 20:09

4 Answers 4

3

The only reason why you would want to route your js through a php script is if you are, for some reason, dynamically generating or modifying the javascript. Otherwise it makes much more sense to link the js file directly. This will allow your web server to handle the request as a static file rather than bottlenecking it through PHP.

Sign up to request clarification or add additional context in comments.

Comments

1

Obviously it's faster to load it straight through with the second example. No PHP interpreter to load, no logic whatsoever, just downloads the file.

One possible reason for the first example is unique dynamically generated JS, or to prevent direct access to the JS source by some additional verification that occurs before the JS is output.

Comments

0

in case of loading from js file, its almost static codes or plugins that do not change per request but in case of loading from php file with param we can change the response or file content easily just like as in php files

Comments

0

You can try replacing your line with something like this:

   <?php
   echo("<script type=\"text/javascript\">\n");
   require("myscript.php?id=1");
   echo("</script>\n");
   ?>

It can be place anywhere.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.