I have written a script (http://jsfiddle.net/vishnukanwar/yqH5B/) using jQuery which shows a social-like_button div on page load. While this div is shown everything else is blurred.
My trouble is, this jQuery script is working fine on my desktop (locally and on jsfiddle) but once I post it to Blogger, it doesn't work.
I feel Blogger does not load jQuery synchronously (even it is asked for) that is why it shows 'jQuery is undefined' error.
var jq = document.createElement('script');
//jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js";
jq.src = "https://code.jquery.com/jquery-1.10.1.min.js";
jq.onload = jq.onreadystatechange = loadPopupBox; // for function def check [link][2]
document.getElementsByTagName('head')[0].appendChild(jq);
Can anyone tell me how can I add jQuery dynamically and synchronously in Google Blogger without modifying my Blog template?
...and here is the code which works absolutely fine for Blogger.com. I added this at www.tcft.in
<script>
function MyScript ()
{
if (typeof jQuery === "undefined") {
alert ("jQuery is undefined");
} else {
alert ($("head").text());
}
}
function LoadJQuery ( onload )
{
if (typeof jQuery !== "undefined") {
if ( typeof onload !== "undefined" ) script.onload = onload;
} else {
var script = document.createElement('script');
if ( typeof onload !== "undefined" ) script.onload = onload;
script.src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js";
script.async = false;
document.head.appendChild(script);
}
}
LoadJQuery( function () { MyScript () });
</script>
Related
So i am working on a simple javascript widget and i started up by followinf this tutorial. I am loading jquery dynamically like below:
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '2.1.4') {
UPDATE, Here is how i'm loading jQuery
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js");
document.documentElement).appendChild(script_tag);
//Once loaded load other javascripts
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
}
Following is my scriptLoadHandler function:
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
Now, in the main method i'm trying to load Bootstrap js like this:
function main() {
console.log("undefined" == typeof jQuery);
var head = document.getElementsByTagName("head")[0];
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js";
head.appendChild(js);
}
But it's still giving me above error even though the order in which they load is correct and when i check console log it gives me false which means jQuery is defined.
Check if JQuery is loaded before of bootstrap loading request. If JQuery is not already loaded bootstrap can not be loaded
//Load jquery here
You're not loading jQuery there.
You should either create a SCRIPT element in the DOM before this script with src your jQuery lib location, or load it dynamically after the line I've quoted (i.e. create the script tag, set the src to your jquery lib relative or absolute URL/URI, add the onloaded event handler to execute scriptLoadHandler and eventually append the new script to the DOM)
Easiest way is to load the script via a script TAG BEFORE the script you're using.
EDIT: after more information by OP, here is the solution:
check for the version of jQuery: if it's not the one you want, load it.
After you've loaded the jQuery version you need (or if it's already loaded), load Bootstrap.
JSFiddle: http://jsfiddle.net/1h6emjwu/2/
function loadScript(src, callback) {
var js = document.createElement('script');
js.src = src;
js.type = 'text/javascript';
if (typeof callback === 'function') {
js.addEventListener('load', callback);
}
document.body.appendChild(js);
}
var myScript = function () {
//alert(window.jQuery.fn.jquery);
alert($.fn.modal ? 'Bootstrap loaded' : 'Bootstrap not loaded');
}
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '2.1.4') {
window.oldJQuery = window.jQuery; // so that you can return back whenever you want
loadScript('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js', function () {
loadScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', myScript);
});
} else {
loadScript('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js', myScript);
}
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.
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 TextBox and a Button:
If the value inside the Textbox is 1 (just emulating a condition)) I need to load jQuery on the fly and use a document Ready function :
I tried this :
function work() //when button click
{
if (document.getElementById('tb').value == '1')
{
if (typeof jQuery == 'undefined')
{
var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-git2.js";
document.getElementsByTagName('head')[0].appendChild(script);
$(document).ready(function ()
{
alert('');
});
}
}
}
But it says :
Uncaught ReferenceError: $ is not defined
I assume it's because the line : $(document).ready(function ()....
But I don't understand why there is a problem , since i'm, loading jQuery BEFORE I use $...
Question :
How can I fix my code to work as desired ?
JSBIN
You are missing the script onload handler:
var script = document.createElement('script');
// do something with script
// onload handler
script.onload = function () {
// script was loaded, you can use it!
};
Your function becomes:
function work() {
if (document.getElementById('tb').value != '1') { return; }
if (typeof jQuery != 'undefined') { return; }
// jQuery is undefined, we will load it
var script = document.createElement('script');
script.src = "http://code.jquery.com/jquery-git2.js";
document.getElementsByTagName('head')[0].appendChild(script);
// load handler
script.onload = function () {
// jQuery was just loaded!
$(document).ready(function () {
alert('');
});
};
}
Also, do not forget script.onreadystatechange for IE compatibility.
script.onreadystatechange = function () {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
// script was loaded
}
}
Also seems that YepNope would be a good option, too.
JSBIN DEMO
Using YepNope would probably a good option in this case.
yepnope([
{
test: window.jQuery,
nope: 'path/url-to-jquery.js',
complete: function() {
$(document).ready(function() {
//whatever you need jquery for
});
}
}
]);
You can just put that in the head of your document, and it will only load jquery if window.jQuery isn't defined. It's much more reliable (and simpler) than script.onload or script.onreadystatechange. the callback complete will only be called once jquery is loaded, so you can be sure that $ will be defined at that point.
Note: if you're using Modernizr.js on your site, there's a good chance yepnope is already bundled into that script.
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.