Can't get jQuery to load in IE8 or IE9 - javascript

I have a header that runs off a js file which can be included on other people's sites, however in IE8 and IE9, I get:
'$' is undefined
in the console.
My code only utilizes jQuery if it is IE8 or IE9 because of cross domain issues which are taken care of with the built in functions in the jQuery library. When browsing on WordPress sites the included script works fine, but on another site without jQuery loaded beforehand, it does not work, and the code I use to include jQuery in the header before loading the jQuery code also does not work.
var isIE = getInternetExplorerVersion();
if (isIE == 8 || isIE == 9) {
// Insert jQuery <script> to <head>.
var head = document.getElementsByTagName( 'head' )[0], script;
script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';
head.insertBefore( script, head.lastChild );
// Run jQuery test
$('html').click(function(){
// Runs without issue on sites that ALREADY have jQuery loaded when IN IE.
alert('Clicked while in IE');
});
} else {
// Runs without issue when not on IE.
alert('Not in IE');
}
For those wondering, this is the function for figuring out the IE version (irrelevant in this case as it works):
function getInternetExplorerVersion() {
var rv = -1; // Return value assumes failure.
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;
}

You don't need to write custom code to check for the IE version. IE ships this "feature"(;
This is the solution from when jQuery 2.0 was released
<!--[if lt IE 9]>
<script src="jquery-1.9.0.js"></script>
<![endif]-->
<!--[if gte IE 9]><!-->
<script src="jquery-2.0.0.js"></script>
<!--<![endif]-->
More on conditional comments for Internet explorer here.

First of all, to solve your problem directly, you are loading the script asynchronously (read: out of order). Therefore, the code after you try loading jQuery doesn't necessarily mean jQuery is loaded at that point. Since you created a script element, you could attach an onload to it
script.onload = function(){
// This will execute when the script you loaded is loaded
}
To answer the other problem, as to why you're loading jQuery based on a browser version, I suggest you use the latest 1.x.x versions of jQuery. They are compatible with IE6+ as well as newer browsers. No need to check for versions.
Your script could have been condensed to:
;(function(ready){
if(jQuery) return ready();
var script = document.createElement('script');
document.head.appendChild(script);
script.onload = ready;
script.src = "path/to/jquery.1.x.x.js";
}(function(){
// Code here runs when ready
}));

First, thank you for all of your answers.
While they were helpfull they could not solve the issue since jQuery must exist on the page before this page is loaded, and injecting it into the head even after this js file is loaded will not work.
To solve the issue I've created another js file to come before this one. In that file it checks whether jQuery is on the page and the browser is one that is incompatible with our xdomain script and if it is, then we add the jquery file via script, and add the js file with all of our functionality afterwards.
File 1:
(function(ready) {
'use strict';
var isIE = getInternetExplorerVersion();
if ((isIE == 8 || isIE == 9) && window.jQuery) {
// On IE and jQuery exists
return ready;
} else if (isIE == 8 || isIE == 9) {
// On IE and jQuery doesn't exit
var head = document.getElementsByTagName( 'head' )[0];
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';
script.onload = ready;
document.head.appendChild(script);
return ready;
} else {
// Not on IE
return ready;
}
script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'http://www.test.com/path/to/other/js_file.js';
script.async = true;
head.insertBefore( script, head.lastChild );
})();
function getInternetExplorerVersion() {
var rv = -1; // Return value assumes failure.
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;
}
File 2 (js_file.js from above):
(function(ready) {
var isIE = getInternetExplorerVersion();
if (isIE == 8 || isIE == 9) {
// Run jQuery test
$('html').click(function(){
// Runs without issue on sites that ALREADY have jQuery loaded when IN IE.
alert('Clicked while in IE');
});
} else {
// Runs without issue when not on IE.
alert('Not in IE');
}
})();

Related

How to add jQuery in Google Blogger without modifying the template?

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>

Javascript resource not loading in ie7

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.

How can I load jQuery if it is not already loaded?

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.

Dynamic, cross-browser script loading

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

Why does jQuery load twice in my GreaseMonkey Script

for some reason my Firefox4+GreaseMonkey Script loads jQuery twice. I copy'n'pasted the following snippet, the "test" alert shows twice.
Regards
var $;
// Add jQuery
(function(){
if (typeof unsafeWindow.jQuery == 'undefined') {
var GM_Head = document.getElementsByTagName('head')[0] || document.documentElement,
GM_JQ = document.createElement('script');
GM_JQ.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js';
GM_JQ.type = 'text/javascript';
GM_JQ.async = true;
GM_Head.insertBefore(GM_JQ, GM_Head.firstChild);
}
GM_wait();
})();
// Check if jQuery's loaded
function GM_wait() {
if (typeof unsafeWindow.jQuery == 'undefined') {
window.setTimeout(GM_wait, 100);
} else {
$ = unsafeWindow.jQuery.noConflict(true);
letsJQuery();
}
}
// All your GM code must be inside this function
function letsJQuery() {
alert("test");
}
This is probably because the target page is loading frames or iframes.
Add these lines to the top of the code-portion of your script:
if (window.top != window.self) //-- Don't run on frames or iframes
return;
Also, if you are just using FF + GM, don't bother with all that rigamarole to load jQuery. GM now works with the later jQuery versions.
Just add a line like:
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js
into your script's metadata block. jQuery will be copied once onto your local machine and run from there -- eliminating what can sometimes be a few seconds delay in your script's runtime.
And such scripts can run in Chrome, if you use one of the GM-emulating extensions like TamperMonkey.

Categories