Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include jQuery in an external .js file?

I want to provide my clients a simple code to insert and get my plugin.

The code:

<div id='banner-lujanventas'></div>
<script src="http://lujanventas.com/plugins/banners/script.js" type="text/javascript"></script>

The problem is that my plugin only works with jQuery. How do I check if a version of jQuery is installed on my script.js file and if not include it? (I can only modify my /script.js file)

like image 213
lisovaccaro Avatar asked Feb 20 '23 07:02

lisovaccaro


1 Answers

Make your own script element :

if (typeof jQuery === "undefined") {
    var script = document.createElement('script');
    script.src = 'http://code.jquery.com/jquery-latest.min.js';
    script.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(script);
}

//edit
window.onload = function() {
    $(function(){ alert("jQuery + DOM loaded."); });
}

You must put your real onload code in a window.onload() function, and NOT in a $(document).ready() function, because jquery.js is not necessary loaded at this time.

like image 125
zessx Avatar answered Feb 27 '23 05:02

zessx