Using external JavaScript file that is not compliant with noconflict

I have a situation where i need to load an external JavaScript file from a vendor. That JavaScript file requires jQuery and uses dollar signs in the script.

My site, however uses jQuery in noconflict mode so when in include the js file, I get an error that $ is not a function.

Is there a way that i can include this script so it works with my site in noconflict mode?

Answer

If you have PHP installed on your server you can create some kind of proxy, that fetches that external file from original source, wraps it around IIFE and returns it, like this:

<?php
echo "(function($) {";
echo file_get_contents("http://link.to.external/script.js");
echo "}(jQuery));";
?>

It will make $ alias to jQuery, but only inside this function, so this script will work, but other scripts won’t be affected.

Of course you can use some other language than PHP.

Also if you have huge traffic on your website, you should consider caching the result, for example for 15 minutes.

Leave a Reply

Your email address will not be published. Required fields are marked *