How do i create a script element to include jquery - javascript

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);
})();

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")
}
}
})

Load jQuery First After DOMContentLoaded

I am trying to load some scripts after DOMContentLoaded event and I am trying to use the following script for this. I'm not sure if the following is the best way to do this but I am having an issue with the following code because I need to load jquery first because my other scripts are depend on it. I have no idea how to do this any help would be greatly appreciated. Thank you very much.
<script>
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
document.getElementsByTagName('body')[0].appendChild(script);
var script1 = document.createElement('script');
script1.src = '/myscript1.js';
document.getElementsByTagName('body')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = '/myscript2.js';
document.getElementsByTagName('body')[0].appendChild(script2);
});
</script>
Please know that dynamic scripts behave as async by default, which means that the script that loads first will also run first. So, the issue might be here that myscript1.js & myscript2.js are very small scripts and thus it loads and runs first before jquery script could load. To fix this you can pass script.async=false to each script so that script loads and run in the order they are being added to the document like:
document.addEventListener('DOMContentLoaded', function() {
var script = document.createElement('script');
script.src = 'https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script);
var script1 = document.createElement('script');
script1.src = '/myscript1.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script1);
var script2 = document.createElement('script');
script2.src = '/myscript2.js';
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script2);
});
and if you want to keep things DRY (Don't repeat yourself), you can use a helper function like:
document.addEventListener('DOMContentLoaded', function() {
function loadScript(src) {
let script = document.createElement('script');
script.src = src;
script.async = false;
document.getElementsByTagName('body')[0].appendChild(script);
}
loadScript('https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.12.4.min.js');
loadScript('/myscript1.js');
loadScript('/myscript2.js');
});

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

jquery from google CDN is not defined

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>

Script does not work intendedly

This script (for Greasemonkey) doesn't work intendedly.
I want to insert an script, and after the script loaded, replace text "Download" to Japanese word (I will use "TEST" instead.).
(function() {
if ((document.URL.match("www.youtube.com/watch?"))||(document.URL.match("c.youtube.com/videoplayback?"))) {
var head = document.getElementsByTagName('head')[0]; //Working
var script = document.createElement('script'); //Working
script.type = 'text/javascript'; //Working
script.src = 'http://userscripts.org/scripts/source/25105.user.js'; //Working
script.onload = 'document.getElementsByClassName("yt-uix-button-content")[0].innerHTML.replace("Download","TEST")'; //Not working.
head.appendChild(script); //Working
};})();
What is the problem?
You have to make sure that the elements are already loaded.
Which means, after body content is loaded you can query elements in the body.
This leads to the following solution.
on the BODY tag you have to add the following
<body onload="myOnloadFunc()">
then you have to create the myOnloadFunc as follows:
<script type="text/javascript>
function myOnloadFunc () {
// in here you should place the original code you have created.
if ((document.URL.match("www.youtube.com/watch?"))|| (document.URL.match("c.youtube.com/videoplayback?"))) {
var head = document.getElementsByTagName('head')[0]; //Working
var script = document.createElement('script'); //Working
script.type = 'text/javascript'; //Working
script.src = 'http://userscripts.org/scripts/source/25105.user.js'; //Working
script.onload = 'document.getElementsByClassName("yt-uix-button-content")[0].innerHTML.replace("Download","TEST")'; //Not working.
head.appendChild(script); //Working
}
</script>

Categories

Resources