jquery from google CDN is not defined - javascript

I am trying to inject jquery CDN by javascript. The following code, however, does not seem to work giving me an error: "$ is not defined". Any help will be appreciated!
var jqry = document.createElement('script')
jqry.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js')
jqry.setAttribute('type', 'text/javascript')
var jqui = document.createElement('script')
jqui.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
jqui.setAttribute('type', 'text/javascript')
document.head.appendChild(jqry)
document.head.appendChild(jqui)
if (typeof jQuery == 'undefined') {
alert('no jquery')
}
$... // codes using jquery

Scripts are being loaded asynchronously.
Listen onload event of the script element as script is not really loaded when if-condition is executed.
var jqry = document.createElement('script')
jqry.setAttribute('src', 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js')
jqry.setAttribute('type', 'text/javascript');
document.head.appendChild(jqry)
jqry.onload = function() {
if (typeof jQuery == 'undefined') {
alert('no jquery')
} else {
alert('Loaded!');
var jqui = document.createElement('script');
jqui.setAttribute('src', '//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
jqui.setAttribute('type', 'text/javascript');
document.head.appendChild(jqui);
jqui.onload = function() {
alert('jquery-ui Loaded!');
}
}
}
A generalized function to load scripts asynchronously:
function loadScript(src, callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.head.appendChild(script);
script.onload = callback || function() {};
}
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js', function() {
alert('jQuery Loaded!');
loadScript('//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js')
})

Try this:
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src","https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js");
document.getElementsByTagName("head")[0].appendChild(fileref);
<head></head>
OR
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js";
document.head.appendChild(script);
<head></head>

Related

Use jQuery without Script tag in head

So I want to make jQuery load inside my script. the user doesn't have to add the <script> to the head, but the script adds automatically. I tried using:
(function() {;
var script = document.createElement("SCRIPT");
script.src = '/src/jquery-embed.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
} else {
window.setTimeout(function() {
checkReady(callback);
}, 20);
}
};
checkReady(function($) {
//code here
fucntion callbutton {
console.log("i return as not defined when called by a button")
}
when I add it, it works fine but all my functions break. How can I go about this without screwing up more?
edit: Link to the file im working on here
Per discussion, to achieve your goal you must ask your clients to delay their script execution until you've loaded your libraries (jQuery in this case).
Shown below is all that is necessary to accomplish the loading:
var script = document.createElement('SCRIPT');
document.getElementsByTagName('head')[0].appendChild(script);
script.src = 'https://code.jquery.com/jquery-3.5.1.min.js';
script.onload = () => {
document.dispatchEvent(new CustomEvent('doYourThing'));
};
Then, your users would use this code:
document.addEventListener('doYourThing', ()=>{
// End user code that relies on jQuery goes here
});
Here is a plunkr that demonstrates the principle.
You forgot document.body.appendChild() and you also forgot to add the parentheses after callbutton
change it to this:
(function() {
var script = document.createElement("SCRIPT");
document.body.appendChild(script);
script.src = '/src/jquery-embed.js';
script.type = 'text/javascript';
document.getElementsByTagName("head")[0].appendChild(script);
var checkReady = function(callback) {
if (window.jQuery) {
callback(jQuery);
} else {
window.setTimeout(function() {
checkReady(callback);
}, 20);
}
};
checkReady(function($) {
//code here
function callbutton(){
console.log("i return as not defined when called by a button")
}
}
})

how to include script file in head section when condition is true?

I am trying to include jquery into section, if condition is true. For some reasons script doesnt work for me, not sure what is wrong
function loadScript() {
var currentLocation = String(window.location);
var c = currentLocation.includes('test')
if(c===true){
//document.write('<scr'+'ipt type="text/javascript" src="assets/jquery.js"></scr'+'ipt>');
console.log(c);
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "jquery.js";
//head.appendChild(script);
document.getElementsByTagName('head')[0].appendChild(script);
alert("asdsad");
}
else{
console.log('error');
}
}
loadScript();
Any help is appreciated
function loadJQueryIfMatch(keyword) {
if (window.location.href.includes(keyword)) {
var script_tag = document.createElement('script');
script_tag.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js');
document.head.appendChild(script_tag);
}
}
loadJQueryIfMatch("test");
Your code is fine currentLocation.includes('test') is a case sensitive only.
load script in codepen

Cannot call function from dynamically loaded javascript file

I'm loading a javascript external file from another javascript file present in the document and since its loaded, I want to call a function from the loaded js file.
Here is the load function:
function loadScript(url) {
var head = window.top.document.getElementsByTagName('head')[0];
var script = window.top.document.createElement('script');
script.src = url;
script.type= "text/javascript";
head.appendChild(script);
if(script.readyState) { //IE
script.onreadystatechange = function() {
if ( script.readyState === "loaded" || script.readyState === "complete" ) {
script.onreadystatechange = null;
console.log("[BANDEAU] script loaded");
testAlert();
}
};
} else { //Others
script.onload = function() {
console.log("[BANDEAU] script loaded");
testAlert();
};
}
}
So it works nice because the javascript file is succesfuly loaded but I cannot access the testAlert() method from the loaded javascript file, as I try in the code above, right after printing that the script is loaded. When I try to get the type of the function with typeOf on window[testAlert], I get an undefined. But when I try to execute the testAlert() method in the developer console, it works perfectly. Does anyone see what I'm doing wrong ?
Does the position in the DOM between the caller javascript file and the loaded javascript file might be the reason ?
You need to assign the load handlers BEFORE changing the src
function loadScript(url) {
var head = document.getElementsByTagName('head')[0]; // window.top in frames/iFrames
var script = document.createElement('script');
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function() {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
console.log("[BANDEAU] script loaded");
testAlert(); // window.top.testAlert() if needed
}
};
}
else {
script.onload = function() {
console.log("[BANDEAU] script loaded");
testAlert(); // window.top.testAlert() if needed
};
}
script.src = url;
head.appendChild(script);
}
In addition to what mplungjan said, I'm pretty sure you'd have to do an eval() on the loaded script in order to have a legitimate address for the call to testAlert().
Also, check out this link for more info.

Include the jquery file dynamically [duplicate]

This question already has answers here:
Load jQuery with Javascript and use jQuery
(9 answers)
Closed 9 years ago.
I want to include the jquery file dynamically when I need to it.
But there is a problem, the error message that appear $ is not defined
What I done:
// include the file dynamically.
var parent, script;
parent = document.getElementsByTagName('head')[0];
script = document.createElement('script');
script.type = "text/javascript";
script.src = "includes/jquery.js";
parent.appendChild(script);
// The usage
$('#box').remove();
For IE, I think you need to use the onreadystatechange callback. E.g.
script.onload = script.onreadystatechange = function() {
if (!script.readyState || script.readyState == 'loaded' ||
script.readyState == 'complete') {
$('#box').remove();
}
};
Handle onload event to make sure your script is loaded before you use it
script.onload = function () { $('#box').remove() }
parent.appendChild(script);
try this:
(function () {
function loadScript(url, callback) {
var script = document.createElement("script")
script.type = "text/javascript";
if (script.readyState) { //IE
script.onreadystatechange = function () {
if (script.readyState == "loaded" || script.readyState == "complete") {
script.onreadystatechange = null;
callback();
}
};
} else { //Others
script.onload = function () {
callback();
};
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}
loadScript("includes/jquery.js", function () {
//jQuery loaded
console.log('jquery loaded');
$('#box').remove();
});
})();

How do i create a script element to include jquery

Im trying to write a script that will append the jquery cdn script
to the body of the document.
function addJquery() {
url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.body.appendChild(script);
}
addJquery();
What am i doing wrong here
You can't add scripts to the body and have them execute. Late-loaded scripts must be loaded through the head element:
(function addJQuery() {
var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
var script = document.createElement('script');
script.url = url;
script.onload = function() { addJQuery(); }
document.head.appendChild(script);
}());
However, this loads jQuery regardless of whether it's already loaded, so that's no good. Here's what you generally want instead:
(function loadMyCode() {
// do we have jquery? if not, load it.
if (typeof jQuery === "undefined") {
var url = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
var script = document.createElement('script');
script.url = url;
script.onload = function() {
// this will run after jquery gets loaded
loadMyCode();
}
document.head.appendChild(script);
return;
}
// if we get here, we know we have jquery
//
// rest of the code goes here.
}());
This is another way
(function () {
var li = document.createElement('script');
li.type = 'text/javascript';
li.src= "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
li.async=true;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(li, s);
})();

Categories

Resources