简体   繁体   中英

Including external javascript which doesn't honor closure usage

I have to include an external javascript file as part of a Drupal project I'm working on. Unfortunately, this external file doesn't make correct use of closures, for example:

(function($) {
    function test() {...}
})(jQuery);
function test2() {
    console.log($('#xyz').val());
}

Which leads to a '$ is undefined' error whenever test2() is executed.

I know that Drupal makes sensible use of closures to allow harmonious coexistence of libraries, which is very useful, but in this case it'll be a nightmare to get the team responsible for said external JS file to make the necessary changes (and will also involve trying to explain to the "experts" responsible).

Is there any way that I can give this external file access to use $ as a pointer to jQuery? Ideally I'd like some solution which doesn't involve a huge workaround at my end, but can still make use of the external version.

Failing that, I'll just take a local copy, and fix accordingly.

Thanks!

只需分配全局。

window.$ = jQuery

You will either need to take a copy and modify it to suit, or use PHP to grab the file and output it, for example if you pointed the javascript src to a local php file, in that php file you could do something like

$js = file_get_contents("externaljsfile");

echo ";(function($) {";

echo $js;

echo "})(jQuery);";

There is a way i heard of, of using imported javascript which may possibly work (javascript macro's?), however i've never read up on them (if they even exist) and they wouldn;t be supported by enough browsers to be a viable solution anyway

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