Load Jquery with JavaScript and Use Jquery

Load jQuery with Javascript and use jQuery

There's a working JSFiddle with a small example here, that demonstrates exactly what you are looking for (unless I've misunderstood your request): http://jsfiddle.net/9N7Z2/188/

There are a few issues with that method of loading javascript dynamically. When it comes to the very basal frameworks, like jQuery, you actually probably want to load them statically, because otherwise, you would have to write a whole JavaScript loading framework...

You could use some of the existing JavaScript loaders, or write your own by watching for window.jQuery to get defined.

// Immediately-invoked function expression
(function() {
// Load the script
const script = document.createElement("script");
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js';
script.type = 'text/javascript';
script.addEventListener('load', () => {
console.log(`jQuery ${$.fn.jquery} has been loaded successfully!`);
// use jQuery below
});
document.head.appendChild(script);
})();

Dynamically load jquery in plain javascript

You're supposed to move your own code into the callback, to where it says // Yay.... Only then is your code run after jQuery was loaded.

getScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js', function() {
// Yay jQuery is ready \o/

$('body').empty().append($('div:first'));
// Delete first and second child divs
for (var i = 0; i < 2; i++) {
$('div:first div:first').remove();
}
});

How do I use JQuery in my Javascript?

JQuery is a JavaScript Library. It simplifies JavaScript programming. It is a lightweight. It takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code. It also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

The jQuery library contains the following features:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

Downloading jQuery

There are two versions of jQuery available for downloading:

  • Production version - this is for your live website because it has
    been minified and compressed.
  • Development version - this is for testing and development
    (uncompressed and readable code).

The jQuery library is a single JavaScript file, and you reference it with the HTML tag (notice that the tag should be inside the section):

<head>
<script src="jquery-3.1.1.min.js"></script>
</head>

jQuery CDN

If you don't want to download and host jQuery yourself, you can include it from a CDN (Content Delivery Network).
Both Google and Microsoft host jQuery.

To use jQuery from Google or Microsoft, use one of the following:

Google CDN:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

Microsoft CDN:

<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
</head>

One big advantage of using the hosted jQuery from Google or Microsoft:

Many users already have downloaded jQuery from Google or Microsoft when visiting another site. As a result, it will be loaded from cache when they visit your site, which leads to faster loading time. Also, most CDN's will make sure that once a user requests a file from it, it will be served from the server closest to them, which also leads to faster loading time.

You can learn more about JQuery from http://www.w3schools.com/jquery/default.asp

Include jQuery in the JavaScript Console

Run this in your browser's JavaScript console, then jQuery should be available...

var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);
// ... give time for script to load, then type (or see below for non wait option)
jQuery.noConflict();

NOTE: if the site has scripts that conflict with jQuery (other libs, etc.) you could still run into problems.

Update:

Making the best better, creating a Bookmark makes it really convenient, let's do it, and a little feedback is great too:

  1. Right click the Bookmarks Bar, and click Add Page
  2. Name it as you like, e.g. Inject jQuery, and use the following line for URL:

javascript:(function(e,s){e.src=s;e.onload=function(){jQuery.noConflict();console.log('jQuery injected')};document.head.appendChild(e);})(document.createElement('script'),'//code.jquery.com/jquery-latest.min.js')

Below is the formatted code:

javascript: (function(e, s) {
e.src = s;
e.onload = function() {
jQuery.noConflict();
console.log('jQuery injected');
};
document.head.appendChild(e);
})(document.createElement('script'), '//code.jquery.com/jquery-latest.min.js')

Here the official jQuery CDN URL is used, feel free to use your own CDN/version.

Load jQuery dynamically

From the jQuerify bookmarlet :

function getScript(url, success) {
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState
|| this.readyState == 'loaded'
|| this.readyState == 'complete')) {
done = true;
success();
script.onload = script.onreadystatechange = null;
head.removeChild(script);
}
};
head.appendChild(script);
}
getScript('http://code.jquery.com/jquery-latest.min.js',function() {
// Yay jQuery is ready \o/
});​

How to dynamic load Jquery inside a JavaScript Class constructor and proceed the execution only after jquery has been fully loaded

That's the solution I've found:

// MyClass.js

var counterLoopLoad = 0;

class MyClass {

constructor(){
// do the code that does not need jQuery
return this.Init()
}

JqueryLoader() {
// Loop Breaker
counterLoopLoad ++;

if (counterLoopLoad == 100) {
throw 'I need jQuery in order to do what I am suppose to do!';
}

var __jquery = document.createElement('script');
__jquery.src = "http://code.jquery.com/jquery-latest.min.js";
__jquery.type = 'text/javascript';

// if needed ....
// __jquery.onload = function() {
// some code here
//
// };

// must be prepend !!! append won't work !!!!
document.head.prepend(__jquery);

// here is the point that makes all work !!!!
// without setTimeOut, the script will get in a loop !

var that = this;
setTimeout(function () {
that.Init();
}, 500);
}

Init() {
if (typeof jQuery == 'undefined') {
return this.JqueryLoader();
}

jQuery.ajax(...);
}
}

Load jQuery in a js, then execute a script that depends on it

You should first check to make sure they do not already use jquery so something like:

if (jQuery) {  
// jQuery is loaded
} else {
// jQuery is not loaded
}

Secondly, you should make sure you use jQuery in no conflict mode and do not use the $ operator as it may be claimed by another script library.

Then to embed, declare this function:

function load_script (url)
{
var xmlhttp;
try {
// Mozilla / Safari / IE7
xmlhttp = new XMLHttpRequest();
} catch (e) {
//Other IE
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open('GET', url, false); x.send('');
eval(xmlhttp.responseText);
var s = xmlhttp.responseText.split(/\n/);
var r = /^function\s*([a-z_]+)/i;

for (var i = 0; i < s.length; i++)
{
var m = r.exec(s[i]);
if (m != null)
window[m[1]] = eval(m[1]);
}
}

Then call it:

load_script('http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js');

Hope this helps.



Related Topics



Leave a reply



Submit