I have a js file that in which i want to include jquery. in order to include the jquery script i am using this clode:
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
this works, I can see that incuded the script correctly. My inspector shows that it loaded the script but jquery wont work.
any ideas?
You need to make sure the script you are dynamically loading is actually loaded before attempting to use it.
To do so, use script.onload to fire a callback once the load is completed.
var script = document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js';
script.type = 'text/javascript';
document.getElementsByTagName('head') [0].appendChild(script);
script.onload = function () {
/* jquery dependent code here */
console.log($);
};
MDN has an example that's more adaptable to a callback you specify -
// from https://developer.mozilla.org/en-US/docs/Web/API/HTMLScriptElement#Dynamically_importing_scripts
function loadError (oError) {
throw new URIError("The script " + oError.target.src + " is not accessible.");
}
function importScript (sSrc, fOnload) {
var oScript = document.createElement("script");
oScript.type = "text\/javascript";
oScript.onerror = loadError;
if (fOnload) { oScript.onload = fOnload; }
document.currentScript.parentNode.insertBefore(oScript, document.currentScript);
oScript.src = sSrc;
}
Your jQuery code is not working may be caused by jQuery is not loaded yet while browser executing your jQuery code. Use function below to dynamically load jQuery with callback. Put your jQuery code inside a callback function.
function loadScript(url, callback) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url;
if (typeof(callback) === 'function') {
s.onload = s.onreadystatechange = function(event) {
event = event || window.event;
if (event.type === "load" || (/loaded|complete/.test(s.readyState))) {
s.onload = s.onreadystatechange = null;
callback();
}
};
}
document.body.appendChild(s);
}
/* Load up jQuery */
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js', function() {
// Put your jQuery code here.
});
You need to include jQuery inside the HTML code. jQuery won't work for you because your script is loaded before jQuery is loaded.
Related
I'm trying to load jquery to page if it's not loaded. I'll run some code right after loading it. With below code, i am trying to catch it when jquery is loaded.
My code loads jquery correctly but not raising onreadystatechange event.
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'http://localhost:8001/jquery-min.js';
headTag.appendChild(jqTag);
jqTag.onreadystatechange= function () {
if (this.readyState == 'complete') {
this.loadWidget(containerId);
}
};
}
else {
this.loadWidget(containerId);
}
How can i catch it when jquery is loaded?
script tags have an onload event for when the script has loaded
if (typeof jQuery === 'undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.onload = function() {
this.loadWidget(containerId);
}
jqTag.src = 'http://localhost:8001/jquery-min.js';
headTag.appendChild(jqTag);
} else {
this.loadWidget(containerId);
}
In my opinion your code is way too complicated.
Why not do what HTML5 boilerplate has done:
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
If the window.jQuery object isn't detected it elegantly fails over to write out the script tag to include it in native Javascript. You can, of course change the path to whatever you want.
Hope this helps.
I have a JavaScript file, which also uses jQuery in it too. To load it, I wrote this code:
function include(filename)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
head.appendChild(script)
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js');
alert("1");
$(document).read(function(){});
alert("2");
This fires alert("1"), but the second alert doesn't work. When I inspect elements, I see an error which says that $ in not defined.
How should I solve this problem?
You need to execute any jQuery specific code only once the script is loaded which obviously might happen at a much later point in time after appending it to the head section:
function include(filename, onload) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';
script.onload = script.onreadystatechange = function() {
if (script.readyState) {
if (script.readyState === 'complete' || script.readyState === 'loaded') {
script.onreadystatechange = null;
onload();
}
}
else {
onload();
}
};
head.appendChild(script);
}
include('http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js', function() {
$(document).ready(function() {
alert('the DOM is ready');
});
});
And here's a live demo.
You may also take a look at script loaders such as yepnope or RequireJS which make this task easier.
The problem here is probably that, even though you include the script, it doesn't mean it is loaded when you try to do $(document).ready(function(){});. You could look into Google Loader to prevent this problem http://code.google.com/intl/fr-FR/apis/loader/
I've been having trouble trying to insert jQuery and jQuery UI into webpage headers through a Greasemonkey userscript I'm working on. Here's how I'm inserting it:
var ccst1 = document.createElement("script");
ccst1.id = "ccst1";
ccst1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
ccst1.type = "text/javascript";
document.head.appendChild(ccst1);
var ccst2 = document.createElement("script");
ccst2.id = "ccst2";
ccst2.src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js";
ccst2.type = "text/javascript";
document.head.appendChild(ccst2);
The actual insertion process works, but when I've inserted it, using jQuery on the page (e.g. in an html onclick) works, but jQuery UI immediately gives me a "$ is not defined" error AND a "jQuery is not defined" error the second it's inserted. No jQuery UI then works on the page.
I believe what you need is simply a small wait before inserting the new code that requires jQuery.
function jQueryReady() {
if (typeof unsafeWindow.$ == 'undefined') {
setTimeout(jQueryReady, 100);
} else {
loadJQueryUI(); //this is your function or code that depends on jQuery
}
}
Is jquery already defined in the page you are trying to include it into.
Have you tried
$.noConflict()
Is it inside a naked function
(function(){ alert($("#hello")); })();
I have two methods to using jQ with my userscripts. The first is to add jQ to the userscript.
function addJQuery(callback) {
var script = document.createElement("script");
script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
script.addEventListener('load', function() {
var script = document.createElement("script");
script.textContent = "(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
// the guts of this userscript
function main() {
$(document).ready( function() {
// YOUR GM CODE GOES HERE
});
}
// load jQuery and execute the main function
addJQuery(main);
This works, however events can get tricky. What I like to do, if the page already is using jQ (check source) is actually create 2 files. One user.js (the GM script) that injects a into the head. This second file needs to be hosted somewhere (i use dropbox) but this is where all your bacon is located. You can write your jQ as if you are writing the code for the page and not a GM script.
eg
GM.user.js
// ==UserScript==
// #name Name (jQuery)
// #description description
// #namespace my twitter page
// #author me
// #include http://
// ==/UserScript==
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'http://dl.dropbox.com/u/example.js';
head.appendChild(script);
example.js
$(document).ready( function() {
// MY Awesome code here.
});
Whichever method you pick, good luck and have fun.
I've just found a solution to this. It actually did have to do with jQuery not being loaded properly, but none of the other solutions worked for me. Joey Geralnik suggested this, which is working properly:
var ccst1 = document.createElement("script");
ccst1.id = "ccst1";
ccst1.src = "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
ccst1.type = "text/javascript";
document.body.appendChild(ccst1);
function ccst2func() {
var ccst2 = document.createElement("script");
ccst2.id = "ccst2";
ccst2.src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js";
ccst2.type = "text/javascript";
document.body.appendChild(ccst2);
ccst2.addEventListener("load", ccst4func, true);
}
ccst1.addEventListener("load", ccst2func, true);
document.body.insertBefore(concealerPanel, document.body.firstChild);
function ccst4func() {
var ccst4 = document.createElement("script");
ccst4.id = "ccst4";
ccst4.type = "text/javascript";
ccst4.innerHTML = "$('#ccpanelmassiveconstruct').draggable({'handle': '#ccpmchandle', 'constrain': 'parent', 'distance': 20, 'cursor': 'move', 'grid': [10,10], 'scroll': true});\n$('#iframeDragger').resizable();\n$('#ccpmctabs').tabs();";
document.body.appendChild(ccst4);
}
I have a initializor.js that contains the following:
if(typeof jQuery=='undefined')
{
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
headTag.appendChild(jqTag);
}
I am then including that file somewhere on another page. The code checks if jQuery is loaded, and if it isn't, adds it to the Head tag.
However, jQuery is not initializing, because in my main document, I have a few events declared just to test this. I also tried writing some jQuery code below the check, and Firebug said:
"jQuery is undefined".
Is there a way to do this? Firebug shows the jquery inclusion tag within the head tag!
Also, can I dynamically add code into the $(document).ready() event? Or wouldn't it be necessary just to add some Click events to a few elements?
jQuery is not available immediately as you are loading it asynchronously (by appending it to the <head>). You would have to add an onload listener to the script (jqTag) to detect when it loads and then run your code.
e.g.
function myJQueryCode() {
//Do stuff with jQuery
}
if(typeof jQuery=='undefined') {
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'jquery.js';
jqTag.onload = myJQueryCode;
headTag.appendChild(jqTag);
} else {
myJQueryCode();
}
To include jQuery you should use this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="jquery.js">\x3C/script>')</script>
it uses the Google CDN but provides a fallback an has a protocol relative URL.
Note: Be sure to change the version number to the latest version
if window.jQuery is defined, it will not continue to read the line since it is an or that already contains a true value, if not it wil (document.)write the value
see: theHTML5Boilerplate
also: you forgot the quotes, if jQuery is not defined:
typeof window.jQuery === "undefined" //true
typeof window.jQuery == undefined //false ,this is wrong
you could also:
window.jQuery === undefined //true
If you're in an async function, you could use await like this:
if(!window.jQuery){
let script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
}
/* Your jQuery code here */
If you're not, you can use (async function(){/*all the code*/})() to wrap and run all the code inside one
.
Alternatively, refactoring Adam Heath's answer (this is more readable IMO). Bottom line, you need to run the jQuery code AFTER jQuery finished loading.
jQueryCode = function(){
// your jQuery code
}
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
Or you could also wrap it in a function to change the order of the code
function runWithJQuery(jQueryCode){
if(window.jQuery) jQueryCode();
else{
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = jQueryCode;
}
}
runWithJQuery(function jQueryCode(){
// your jQuery code
})
The YepNope loader can be used to conditionally load scripts, has quite a nice, easy to read syntax, they have an example of just this on their website.
You can get it from their website.
Example taken from their website:
yepnope([{
load: 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('local/jquery.min.js');
}
}
}
This site code is solved my problem.
function loadjQuery(url, success){
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0],
done = false;
head.appendChild(script);
// 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);
}
};
}
if (typeof jQuery == 'undefined'){
loadjQuery('http://code.jquery.com/jquery-1.10.2.min.js', function() {
// Write your jQuery Code
});
} else {
// jQuery was already loaded
// Write your jQuery Code
}
http://99webtools.com/blog/load-jquery-if-not-already-loaded/
This is old post but I create one workable solution tested on various places.
Here is the code.
<script type="text/javascript">
(function(url, position, callback){
// default values
url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
position = position || 0;
// Check is jQuery exists
if (!window.jQuery) {
// Initialize <head>
var head = document.getElementsByTagName('head')[0];
// Create <script> element
var script = document.createElement("script");
// Append URL
script.src = url;
// Append type
script.type = 'text/javascript';
// Append script to <head>
head.appendChild(script);
// Move script on proper position
head.insertBefore(script,head.childNodes[position]);
script.onload = function(){
if(typeof callback == 'function') {
callback(jQuery);
}
};
} else {
if(typeof callback == 'function') {
callback(jQuery);
}
}
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){
console.log($);
}));
</script>
Explanation you can find HERE.
I know that IE doesn't have a load event for <script> elements — is there any way to make up for that reliably?
I've seen some talk of things (e.g., requestState == "complete") but nothing very verifiable.
This is to be used so that code can be called after a script is finished loading, so that I don't have to use AJAX to load new sources (thus eliminating issues with cross-domain AJAX).
You can use a script loader like head.js. It has its own load callback and it will decrease load time too.
From the headjs code: (slightly modified to be more portable)
function scriptTag(src, callback) {
var s = document.createElement('script');
s.type = 'text/' + (src.type || 'javascript');
s.src = src.src || src;
s.async = false;
s.onreadystatechange = s.onload = function () {
var state = s.readyState;
if (!callback.done && (!state || /loaded|complete/.test(state))) {
callback.done = true;
callback();
}
};
// use body if available. more safe in IE
(document.body || head).appendChild(s);
}
I want to add that if you don't support IE7 and below, you don't need onreadystatechange stuff. Source: quircksmode.org
Simplified and working code from original answer:
function loadScript(src, callback) {
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.async = false;
if(callback) {
s.onload = callback;
}
document.body.appendChild(s);
}
This is just an extension of ilia's answer. I used scriptTag like this: Works great:
// these 3 scripts load serially.
scriptTag(boot_config.DEPENDENCIES.jquery,function(){
// jquery ready - set a flag
scriptTag(boot_config.DEPENDENCIES.jqueryui,function(){
// jqueryui ready - set a flag
scriptTag(boot_config.DEPENDENCIES.your_app,function(){
// your_app is ready! - set a flag
});
});
});
// these 2 scripts load in paralell to the group above
scriptTag(boot_config.EXTERNALS.crypto,function(){
// crypto ready - set a flag
});
scriptTag(boot_config.EXTERNALS.cropper,function(){
// cropper ready - set a flag
});