I have a little issue bugging me for several hours now, so i come to see you guys for some help.
Here is the situation :
I use jquery-2.1.4.js in my application. If i test my fragment of code outside the application it work correctly but when it is in my application Jquery doesn't load correctly.
Jquery is include correctly in my repository and called in my page before the end of the body tag like this (i moved it away from the head tag thiking it might be the issue but i still got the same error) :
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
I test if Jquery is correctly loaded like this :
if (typeof jQuery == 'undefined') {
// jQuery is not loaded
alert("jquery not loaded,force it");
var jq = document.createElement('script');
jq.type = 'text/javascript';
// Path to jquery.js file, eg. Google hosted version
jq.src = 'js/jquery-2.1.4.js';
document.getElementsByTagName('head')[0].appendChild(jq);
} else {
// jQuery is loaded
alert("jquery is loaded");
}
The issue is here now :), everytime I end up in the not loaded part, and when I force Jquery load, I got an error line 3539 of the Jquery file on the function :
function Data() {
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Data.uid++;
}
With the error message :
This object does not have this property or method : defineProperty
(not sure about the English for this one, my error message is in French).
Just so you know, there is no action done on Load, only when i click a button. Our file with JS codes are in a .include, so i don't know if this is why the error is trigger or not.
Anyway, thanks for taking the time to help me.
Slayner.
You need to include the expando library, since it is not part of standard jQuery. Try adding this:
<script src="//cdn.rawgit.com/cantino/expando/38affee59bffdd87975c492472362c69ce0f6fda/jquery.expando.js"></script>
Right after this:
<script type="text/javascript" src="js/jquery-2.1.4.js"></script>
Okay, so the reason why this did not work for me was that our application is loaded as an IE5 application and is not compatible with JQuery (well not a version from these last few year.)
Related
Please help me by answering with a short theory behind how it works as I would like to understand the logic rather than just get an answer. If you know of any material that explains it for beginners then please reference it. I have spent quite a lot of time researching and have come up blank and find the name or anything that explains this behavior.
My question is and want to understand, I thought the way browsers parse the html is line by line. When it encounters a <script> tag everything else comes to a halt (this basic example) whilst it passes it off to the js interpreter to also complete line by line. Once it has finished it then passes it back to the html parser to continue with the rest of the page
So my question is from the short example below, why is "find" being loaded before backup.js has completed, when I remove backup.js and have jQuery instead the code in console.log(find); works as expected, but when jQuery is removed from html and asked to be added via backup.js, which is still the first tag encountered before the console.log(find); at the bottom, it does not work? I get the following error message:
ReferenceError: $ is not defined
var find = $('.link');
Makes me believe that var find = $('.link'); is being attempted to be accessed before backup.js and jQuery have finished loading, but why is this when "find" comes long after backup.js? Or am I doing something wrong with the Javascript code in backup.js that adds it after rather than earlier?
I have this short piece of html:
<html>
<head>
<!--<script src="https://code.jquery.com/jquery-1.11.1.js"></script>-->
<script type="text/javascript" src="backup.js"></script>
<meta charset="UTF-8">
<title>My Web Page</title>
</head>
<body>
<p>hello</p>
<div class="link">test</div>
<script>
var find = $('.link');
console.log(find);
</script>
</body>
</html>
In backup.js I have this:
if(typeof jQuery=='undefined') {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'https://code.jquery.com/jquery-1.11.1.js';
head.appendChild(script);
console.log('jquery not found');
}
else{
console.log('jquery found');
}
In your backup.js file you load jquery from the server if it does not yet exist. Loading something from the server through an Asynchronous call means it won't stop the page rendering, so what happens is:
The page starts rendering, it comes to backup.js, starts loading jquery from the server, keeps rendering the page while loading jquery, goes all the way to the bottom and then finds $(".link");. In this line of code the symbol "$" means jQuery (I want to use jquery for this part of code), but it might happen that jquery is not yet completely loaded, and so the program breaks and tells you ReferenceError: $ is not defined (or in human: you're trying to use $ but it doesn't exist).
To fix this, you can create a function that gets called when jquery has loaded:
if(typeof jQuery=='undefined') {
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'https://code.jquery.com/jquery-1.11.1.js';
script.onload = function() {
runAfterjQueryLoad();
}
head.appendChild(script);
console.log('jquery not found');
} else {
console.log('jquery found');
}
function runAfterjQueryLoad() {
var find = $('.link');
console.log(find);
}
Working fiddle: http://jsfiddle.net/aj803z7u/
You're right about the page rendering top-down, but always be careful for asynchronous calls (also know as ajax, in case you want to search for more information on the web).
The best way of learning is by doing. Think of a page you want to create and try to do it, searching for tutorials for each single small step (you can always come here on SO and ask questions) .
I have this code in a script we use for initializing all of our applications, it loads the jQuery from the google CDN amongst several other things that all of our applications require. Then when we load the specific program functionality we check to make sure that jquery has loaded, in case the CDN is down. The problem I am running into is it is still loading the second one. If I add a simple alert("Test"); after the line headTag.appendChild(jqTag); it works perfectly, but if I remove the alert it uses the second one. What gives?
They are loaded like so:
<script type="text/javascript" src="i-initializer.js"></script>
<script type="text/javascript" src="i-program.js"></script>
initializer script:
if(typeof jQuery=='undefined'){
var headTag = document.getElementsByTagName("head")[0];
var jqTag = document.createElement('script');
jqTag.type = 'text/javascript';
jqTag.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js';
headTag.appendChild(jqTag);
}
Then in another script we have the following:
if(typeof jQuery=='undefined'){
var header = document.getElementsByTagName("head")[0];
var qtag = document.createElement('script');
qtag.type = 'text/javascript';
qtag.src = 'http://feedback.oursite.com/scripts/jquery-1.8.3.min.js';
qtag.onload = checkjQueryUI;
header.appendChild(qtag);
}
else
{
jQCode();
}
jQCode() {
...
}
This is the technique used by HTML5 Boilerplate. First it loads the Google CDN script, then immediately checks if the global jQuery object exists -- if it doesn't, the CDN failed and a local copy is loaded instead.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.3.min.js"><\/script>')</script>
Your fallback code loads jQuery asynchronously.
That means that the rest of your scripts run before jQuery loads.
Adding an alert() call forces the rest of your code to wait (until you click OK); by the time that happens, jQuery will have loaded.
Instead, you can emit a new <script> tag using document.write() to load it synchronously.
Alternatively, you could wrap the rest of your code in a callback and call the callback(s) after jQuery loads.
If you do it this way, you should use a script loader library, which will handle all of that for you.
Using JavaScript, is there a way to detect whether or not an external script (from a third-party vendor) has completely loaded?
The script in question is used to pull in and embed the markup for a list of jobs and, unfortunately, doesn't make use of any variables or functions. It uses document.write to output all of the content that gets embedded in my page.
Ideally, I'd like to display some kind of loading message while I'm waiting for the external script to load, and if it fails to load, display a "We're sorry, check back later..." message.
I'm using jQuery on the site, but this external script is called before I make the jQuery call.
Here's what the document.write stuff from the external script looks like:
document.write('<div class="jt_job_list">');
document.write("
<div class=\"jt_job jt_row2\">
<div class=\"jt_job_position\">
Position Title
</div>
<div class=\"jt_job_location\">City, State</div>
<div class=\"jt_job_company\">Job Company Name</div>
</div>
");
Attach an function to the load event:
<script type="text/javascript" src="whatever.js" onload ="SomeFunction()" />
As far as your loading... problem goes, try displaying a div for loading and then just display:none-ing it in your onload function. Make sure to handle cases where your script fails to load too, though.
Script tags block downloads, so as long as the content dependent on your script is below where your script it loaded, you should be fine. This is true even if the script is in-line in the body of your page.
This website has a great example of how this works.
This obviously does not work if you're loading the scripts asynchronously.
Scripts without async or defer attributes are fetched and executed immediately, before the browser continues to parse the page.
Source: MDN
You could put a script block after it on the page:
<script src="external_script.js"></script>
<script type="text/javascript">
ExternalScriptHasLoaded();
</script>
Thanks for the assistance above, especially ngmiceli for the Steve Souders link!
I decided to take what's probably a "lazy" approach, and also forego the "loading" message:
$(document).ready(function(){
if ($('.jt_job_list').length === 0){
$('#job-board').html("<p>We're sorry, but the Job Board isn't currently available. Please try again in a few minutes.</p>");
};
});
Pretty simple, but I'm looking to see if an element with the .jt_job_list class is in the dom. If it isn't, I display an error message.
This worked for me: it does however, rely on the newer querySelector interface which most modern browsers support. But if you're using really old browsers, you can use getElement... and run a for loop.
function loadJS(file, callback, error, type) {
var _file = file ;
var loaded = document.querySelector('script[src="'+file+'"]') ;
if (loaded) {
loaded.onload = callback ;
loaded.onreadystatechange = callback;
return
}
var script = document.createElement("script");
script.type = (typeof type ==="string" ? type : "application/javascript") ;
script.src = file;
script.async = false ;
script.defer = false ;
script.onload = callback ;
if (error) {
script.onerror = error ;
}
else {
script.onerror = function(e) {
console.error("Script File '" + _file + "' not found :-(");
};
}
script.onreadystatechange = callback;
document.body.appendChild(script);
}
You could give what ever your looking for an ID
and check whether not the ID has been loaded using document.getElementById("ID");
Is that what your looking for not sure I fully understand?
If you would like to get to the point, here is my question:
Is there any way to call a specific script to load first in javascript?
For more detail, please read below:
I have a javascript file that is loading from the bottom of my HTML <body>. Unfortunately, there is no JQuery in the head, so I have to add it through this javascript file.
What I need to do is add a JQuery lightbox plugin.
My problem is that when I load the page, sometimes JQuery isn't the first thing loaded. So I receive the error "jQuery is not defined". Which will then raise more errors for undefined methods from the plugin.
This doesn't happen all the time, only sometimes. Which makes me think it's a loading/order of operations issue.
Is there any way I can guarantee that my JQuery script is the first thing loaded?
Here is some of my javascript file.
//Get head element
var head = document.getElementsByTagName("head")[0];
//Create and insert JQuery
var jquery = document.createElement('script');
jquery.type = 'text/javascript';
jquery.src = 'http://image.iloqal.com/lib/fe6b/m/1/jquery.1.7.2.js';
head.insertBefore(jquery,head.childNodes[4]);
function thescripts() {
var fancybox = document.createElement('script');
fancybox.type = 'text/javascript';
fancybox.src = 'http://image.iloqal.com/ilejquery.fancybox-1.3.4.pack.js';
head.appendChild(fancybox);
var thebody = document.getElementsByTagName('body')[0];
thebody.appendChild(thediv);
thediv.appendChild(theimg);
//Run fancybox
thebody.onload = function() {
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
};
if(jquery.attachEvent){
jquery.attachEvent("onload",thescripts());
} else {
jquery.onload = thescripts();
}
Any help is appreciated!
Try this. Add this piece of code inside your javascript file which is called from your footer.
<script type="text/javascript">
if(typeof jQuery == 'undefined'){
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></'+'script>');
}
</script>
This will include jquery if its not loaded. I think this will fix your issue.
Using $(function() {...do your stuff here...}); is the way to go to be sure jQuery is loaded before the script is executed, but you could probably make it harder for yourself and do:
thebody.onload = function() {
RunMyjQuery();
}
function RunMyjQuery() {
if (typeof $ === 'undefined') {
setTimeout(RunMyjQuery, 500);
}else{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
}
}
You're calling thescripts immediately, although you try not to. Use this:
jquery.onload = thescripts; // notice no parentheses
Also, your thebody.onload strategy will not work. Use $(document).ready instead:
$(document).ready(function{
$('#lightbox').ready(function() {
$("#lightbox").fancybox().trigger('click');
});
});
I am using Google Custom Search Engine with their new auto-completion feature. I want this whole javascript to be loaded AFTER the page itself is loaded. The original Google code is this:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'some-long-unique-id',
document.getElementById('q'),
'cse-search-box');
});
</script>
<script type="text/javascript" src="http://www.google.com/cse/brand?form=cse-search-box&lang=cs"></script>
I have transformed this code using tutorial about JS dynamic loading to this code:
(function() {
var goog = document.createElement('script'); goog.type = 'text/javascript';
goog.src = 'http://www.google.com/jsapi';
var cse = document.createElement('script'); cse.type = 'text/javascript';
cse.src = 'http://www.google.com/cse/brand?form=cse-search-box&lang=cs';
goog.onload = function() {
google.load('search', '1');
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'some-long-unique-id',
document.getElementById('q'),
'cse-search-box');
});
};
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(cse, s);
s.parentNode.insertBefore(goog, s);
})();
Well, even though I think my solution should work(the same way has Google changed their Analytics on-demand asynchronous code), it doesn't. The page loads fine and as soon as CSE loads, the page goes blank. Something clears the DOM, I suppose its some kind of "Google thing" ? Can someone bring some light on this problem and possibly a working solution ?
Thanks
OK, so by checking Google Loader Developer's Guide and by lots of trying-and-testing I've figured how to change my code so it works as I expected in my question:
(function() {
var goog = document.createElement('script'); goog.type = 'text/javascript';
goog.src = 'http://www.google.com/jsapi';
goog.onload = function() {
google.load('search', '1', {"callback": function() {}});
google.setOnLoadCallback(function() {
google.search.CustomSearchControl.attachAutoCompletion(
'some-long-unique-id',
document.getElementById('q'),
'cse-search-box');
});
};
var cse = document.createElement('script'); cse.type = 'text/javascript';
cse.src = 'http://www.google.com/cse/brand?form=cse-search-box&lang=cs';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(cse, s);
s.parentNode.insertBefore(goog, s);
})()
The main thing is this line:
google.load('search', '1', {"callback": function() {}});
If you don't specify callback (at least empty function as I do), then the whole page goes blank, when Google's CSE loads. I have no idea why, but it works fine now with this dummy callback function.
Hope it helps someone with the same problem.
I guess you can use some js loader (eg yepnope) that allows you to load js on demand and add a callback.
I don't fully-understand what you're trying to achieve. You've asked for someone to suggest how to 'correct' your code, but you haven't given any context, or what you actually want the end-result to be.
Also, the updates you've provided with the function()s you've written- it's not clear how these are being called. In the when the document readyState is complete?
Firstly, I'd suggest using jQuery to wrap up the JavaScript stuff. Yes, Google provide onload events and other helpers for their API, but jQuery will apply to any Javscript, there's no point in using two Javascript frameworks where you don't have to.
The jQuery might be like this:
<script type="text/javascript" language="javascript" src="/js/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" language="javascript">
// Use the jQuery document load functionality.
$(document).ready(function ()
{
// Load the Google API asynchronously. The callback 'GoogleApiLoaded' will be called when the script is fully-loaded.
$.getScript("http://www.google.com/jsapi?key=yourkey", GoogleApiLoaded);
// Load other scripts, do other init code here (non-Google-dependent).
});
function GoogleApiLoaded()
{
// Google-related init here.
// Load the custom search API.
// (Could make the callback an in-line function).
$.getScript("http://www.google.com/cse/brand?form=cse-search-box&lang=cs", CustomSearchApiLoaded);
}
function CustomSearchApiLoaded()
{
google.load('search', '1', LoadCustomSearchControl);
}
function LoadCustomSearchControl()
{
google.search.CustomSearchControl.attachAutoCompletion('some-long-unique-id', document.getElementById('q'), 'cse-search-box');
}
</script>
It might be helpful to break the code apart into different functions, in order to track-down more easily where the problem is. That you have to put in an optional callback on the 'google.load()' function is strange- it may be a bug in the Google code, there are some floating around.
I've used google.load('search', '1', LoadCustomSearchControl), rather than the google.setOnLoadCallback, because as far as I can see they should do the same thing, and using a callback on load() is neater, in my view.
I'd strongly advise you use jQuery (or any JavaScript framework), as it makes life a lot easier.
I'd be interested to see whether what I've suggested works, and if not where it goes wrong. (Make sure to add-in your own JSAPI key).