简体   繁体   中英

load javascript source code direct from .js or through .php

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.

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM