jeudi 23 juin 2016

Provided script uses jQuery's $, but drupal site has noConflict enabled

I have a Drupal 7 site (with jquery-update installed, FWIW). jQuery seems to be referenced by the jQuery object instead of $. This is well documented at https://www.drupal.org/node/171213.

I am trying to make use of a provided script to meet some specific requirements.

The script provided makes use of the $ object, and so I get "TyperError: $ is not a function".

The HTML and script provided looks like:

<div id="grid"><span class="grid-load-error">There was an error loading the interactive grid.</span></div> 
<script type="text/javascript" src="//site.com/tool.js">
</script>

On page load, I get the TypeError message.

I have tried to wrap the loading of the script in a closure:

<div id="grid"><span class="grid-load-error">There was an error loading the interactive grid.</span></div> 
<script type="text/javascript">
    (function($) {
        $(function() {
            // console.log($('#grid').html());
            $.getScript("//site.com/tool.js");
        });
    })(jQuery);
</script>

I know that $ works within the closure - the commented console.log() generates the correct output when uncommented.

I assumed that $.getScript() would fail, as https://api.jquery.com/jquery.getscript/ tells me that the script is executed in the global context (which, if I understand closures correctly $ isn't global here).

Is there a way that I can include this script from the source, or should I edit it to replace "$" with "jQuery"?

Aucun commentaire:

Enregistrer un commentaire