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"?
$.getScript
is a shortcut for $.ajax()
and then jquery being nice just appending the script to <head>
for you. However in your case this won't work as you already found out. So, just create your own $.getScript
Just fetch the script, and then append it to your own <script>
tag and wrap the contents of the fetched script in an iffe
<script id="myLib"></script>
<script>
(function ($){
//$.getScript('./tool.js');
$.ajax({
url: './tool.js',
dataType: "text", //force script response to be treated as plain text
success: function(data) {
var myLib = '(function ($){' + data + '}(jQuery));';
$('#myLib').html(myLib);
}
});
}(jQuery));
</script>
Your script should work fine now. Just make sure that
<script id="myLib"></script>
Comes after jQuery is defined on the page.