user198989
user198989

Reputation: 4665

How to include jQuery library in Javascript without <script src="">

I need to include jQuery library in javascript file (john.js) remotely. I have tried this without any luck;

(function(d, t) {
    var g = d.createElement(t), // create a script tag
        s = d.getElementsByTagName(t)[0]; // find the first script tag in the document
    g.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
    s.parentNode.insertBefore(g, s); // append the script to the DOM
}(document, 'script'));

$( document ).ready(function() {

// My jquery works here

});

I want to fetch a script in javascript way. What is the correct way to do that ?

Upvotes: 3

Views: 3361

Answers (4)

eniacAvenger
eniacAvenger

Reputation: 875

Typically the jquery is called in the html file before custom javascript files are called:

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="app.js"></script>

Upvotes: 0

rnrneverdies
rnrneverdies

Reputation: 15667

The error here is that JQuery is not loaded yet when this code is executed:

$(document).ready(function() { .. }

As is, you get an error like this: $ is undefined (or similar)

You should use the onload event of created script element to be sure it is loaded Jquery.

This sample shown how you can achieve your goal. Good Luck.

var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://code.jquery.com/jquery-latest.js'; // set the source of the script to your script
newScript.onload = function() {
  alert("Script is ready!");
  $(document).ready(function() {
    alert("JQuery is ready!");
  });
};
var head = document.getElementsByTagName("head")[0];
head.appendChild(newScript);

Upvotes: 3

risto
risto

Reputation: 1304

You can use a combination of an XMLHttpRequest and eval to fetch the javascript file dynamically like getScript does for jQuery.

See my fiddle.

Upvotes: 1

MrVinz
MrVinz

Reputation: 874

Here is the answer on how to fetch, coming from an other post :

Adding <script> element to the DOM and have the javascript run?

That beeing said another issue you may have is that when you call your

$( document ).ready(function() {

// My jquery works here

});

Jquery may not be loaded yet

so you can try a recursive function to check if jquery has been loaded with something like that (not teste)...

function launch(callBack){
    if (window.jQuery) {  
       callBack();
    } else {
        setTimeout(function(){launch(callBack);},100);
    }
}
launch(function(){
   $( document ).ready(function() {
     // My jquery works here
   });
});

Upvotes: 1

Related Questions