Using external JavaScript file that is not compliant with noconflict Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using external JavaScript file that is not compliant with noconflict without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

We are here to answer your question about Using external JavaScript file that is not compliant with noconflict - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji