I'm loading jQuery dynamically using JavaScript. For loading jQuery, callback function is defined and in its call back function call doing some jQuery stuff.
Works great in Firefox, chrome and IE9 as expected but in IE8 gives error message like "$ is not defined" mean there is issue with call back function execution in IE8. I have spent a whole day to find out solution but not getting any way.
<body>
<script language="javascript" type="text/javascript">
function loadjQuery(callback) {
var ver = getInternetExplorerVersion();
var body = document.getElementsByTagName('body')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
if (ver == 8.0) {
script.onload = callback.call();
}
else {
script.onload = callback;
}
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js';
body.appendChild(script);
}
loadjQuery(function () {
alert($(window).height());
});
function getInternetExplorerVersion() {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
</script>
</body>
I'm totally stuck. Any help would appreciable?
I used to code this function as well and the following code seems working perfectly:
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
done = true;
// callback function provided as param
if(success != null)
{
success();
}
script.onload = script.onreadystatechange = null;
//head.removeChild(script);
};
};
Related
I am taking a page that does not have jquery referenced in the dom. I need to use some of the jquery functionality, so i figured the best bet is to inject jquery into the existing dom. I got the function idea from Load jQuery with Javascript and use jQuery and How to include jQuery dynamically in any website using pure javascript ....none of these solutions seem to work for me. I am still getting an error not recognizing the jquery selector.
(function() {
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('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js',function() {
// Yay jQuery is ready \o/
});
cards = $('div:first');
$('body').empty().append(cards);
// Delete first and second child divs
first = $('div:first div:first');
$('div:first div:first').css('position', '').css('left', '').css('z-index', '').css('height', '250px').remove();
second = $('div:first div:first');
$('div:first div:first').css('position', 'relative').css('left', '').css('z-index', '').remove();
$('body').empty().append(first).append(second);
})();
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();
}
});
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>
I have a whole bunch of javascript files I need to load in order. However, one of them is not loading in ie7.
Here's the function that does the loading:
function loadScript(url, callback){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = url;
// Attach handlers for all browsers
var done = false;
script.onload = script.onreadystatechange = function()
{
if( !done && ( !this.readyState
|| this.readyState == "loaded"
|| this.readyState == "complete") )
{
done = true;
// Continue your code
callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
And the function calls:
loadScript('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js',function(){
loadScript('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js',function(){
loadScript('http://XXX/js/data.php?rand='+Math.random(),function(){
loadScript('http://XXX/js/jquery.inject.js?rand='+Math.random(),function(){
console.log('a');
loadScript('XXX/js/press.js?rand='+Math.random(),function(){
console.log('b');
inject_press();
});
});
});
});
});
The file that doesn't load i jquery.inject.js, whos code is
console.log('y');
jQuery.prototype.inject = function(a){
...
}
Again this works in all browsers except ie7. The output is
a
b
This is not the best way how to load ECMAscript files. I would name that files to sort them and then load using ASP.NET 4.5 bundling.
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 would like to know how to load an external Javascript into my document from a function.
This is one way:
function loadDaFun() {
var script = document.createElement('script');
script.src = '/path/to/your/script.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}
The #seth's answer is completely right, but you don't need to leave the inserted script element on the DOM, you can remove it just after it is loaded, and also you might want to know when the inserted script is ready to use, for example you can:
function loadScript(url, completeCallback) {
var script = document.createElement('script'), done = false,
head = document.getElementsByTagName("head")[0];
script.src = url;
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
completeCallback();
// IE memory leak
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
Usage:
loadScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
function () { alert('jQuery has been loaded.'); });