简体   繁体   中英

PHP - Using `file_get_contents()` to insert javascript

I'm seeing some related questions, but nothing specific to this case.

This question is asked in the context of Magento, but it by no means would be limited to here.

I have a <head> template that, among the other things a head will do, includes various Javascript files.

There is one script that for general reasons, I would prefer to include from the author's CDN. Unfortunately, the author does not make a version available over HTTPS which will result in users seeing "insecure content" when loading this script (and depending on browser, failing to run the code).

I understand that I can simply save this file to my local domain where it will be available over HTTPS, but as I said, I would prefer to grab this script from the CDN.

As a work around, I have used (in the template):

<script type="text/javascript">
    <?php echo file_get_contents('http://path.to/the/file.js' ?>
</script>

This allows the file to live without an HTTPS version since it is included when PHP is parsed rather than as a separate resource loaded in the browser at run-time.

Assuming I left a comment in the template explaining why this method is used, are there any significant repurcussions I might find by doing it this way?

There are two disadvantages with this approach:

  • The user cannot cache Javascript (which result in slower loading time)
  • You use extra bandwidth and extra connection to download the content from other source (slower loading time again). If it is a high traffic website, it has a great performance impact.

Assuming that the reason that you want to download directly from CDN because you always want an updated script. You can firstly download the content of the script and put it at your server. Have a cron job to re-download the script from CDN once everyday. This will help you get the updated script and as well as a better performance.

I don't know what kind of javascript file we're talking about here. If it's something popular, then the chances are you can a CDN that already hosts it. If that's a random javascript file that you include, then you can do something like this:

  1. Grab the javascript file via curl.
  2. Push grabbed javascript file to your personal CDN.
  3. Link your view files to point that javascript file hosted on CDN.
  4. Set a CRON task to check updates of the javascript source. If found, repeat process 1-2-3.

It may be too much, but it's an option.

One of the downside of your usage would be traffic. You'll use both inbound and outbound traffic since you'll request and serve the javascript each time. You should cache it (and this is one of the reason why CDN's are for) and serve from there.

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