This is what I have in :
<script src="myscript.js" type="text/javascript"></script>
<script type="text/javascript">testfunction("hello");</script>
Inside myscript.js:
if(!window.jQuery)
{
var script = document.createElement('script');
script.type = "text/javascript";
script.src = 'jquery-1.9.0.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
function testfunction(str) {
$(document).ready(function () {
alert(str);
});
}
Of course jQuery is not needed for the current testfunction, but it will be needed. Using this approach, jQuery is downloaded but NOT loaded to the browser when calling to testfunction() (Uncaught ReferenceError: $ is not defined).
What I could do is to load jQuery in a different script before my JS is loaded. In that case, it will work, but I would have three different scripts and that seems to be not elegant in my honest opinion.
Is there any other way to achieve this?
Thanks!