JavaScript: using Flattr API. how to wait until API is loaded? - javascript

I'm trying to use the Flattr JavaScript API. I included the loading code as described.
But FlattrLoader.setup() does not work. I am getting the exception ReferenceError: FlattrLoader is not defined.
I tried both
<script type="text/javascript">
FlattrLoader.setup();
</script>
and
<script type="text/javascript">
window.onload = function(){ FlattrLoader.setup(); }
</script>
That is strange because in the load.js from the API, I see var FlattrLoader = { ... }.
I use Chrome. From its Developer Tools, it seems that the load.js gets loaded (at least it lists it there).
Maybe I must do some extra handling that it waits with the execution until the load.js is really loaded? The only explanation why it fails is that the site-loading itself is finished
before load.js can be loaded. How would such extra handling look like?

My current solution:
function loadFlattr() {
if(typeof(FlattrLoader) == "undefined")
setTimeout(loadFlattr, 100);
else
FlattrLoader.setup();
}
loadFlattr();
Is there any better solution?

since this is an old thread, I don't know if you've fixed this, but you should check out the current version of the documentation. The code is a lot easier and also async now
https://flattr.com/support/integrate/js

Related

call a function onload of external script

I'm playing around with Google Drive API, and noticed that they are calling a handleClientLoad function onload of the client.js.
<script src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
Trying to avoid creating globals, I thought I would start with creating another js file, that would contain a module pattern and return handleClientLoad.
var module = (function (window, $) {
'use strict';
var module = {
handleClientLoad: function () {
console.log('ok, can access');
}
};
return module;
}(window, jQuery));
And then I assumed I could just call the handleClientLoad by doing module.handleClientLoad, but that doesn't seem to be working.
<script src="scripts/main.js"></script>
<script src="https://apis.google.com/js/client.js?onload=module.handleClientLoad"></script>
Questions:
Is it possible to call the module.handleClientLoad from onload of client.js?
Appending onload and calling a function from a script file seems sloppy and obtrusive, no? Is there a cleaner way to know when the client.js has loaded?
Have you tried debugger, and are you sure module. hanfleClientLoad exists at the time the callback is fired?
You can poll for the existence of gapi.client as a global object. Give it a few milliseconds to initialise before invoking its methods.
I found that jQuery.getScript() worked quite nicely for this. Documentation here.
Instead including the <script> tag in the html page, I simply included the following line in my js file:
jQuery.getScript( "https://apis.google.com/js/api.js", handleClientLoad );
It might require slight tweaking for the way you structured your module, but I think this will be easier than passing a parameter to your <script> tag (at least I found it easier).
I know this is old, but I was messing around with this because this was related to a question on a test I was studying for. You can use onload like this when you call the script:
<script src="https://apis.google.com/js/client.js" onload="handleClientLoad()"></script>
For anyone wanting to know why this won't work:
<script src="https://apis.google.com/js/client.js">handleClientLoad()</script>
It's because any code between a script tag with "src=" in it will be ignored.
And I'm not sure why using onload= in the script tag calling the external script is any more obtuse than appending ?onload=module.handleClientLoad to the source? But that's just me.
In the end, I'm not sure why exactly this was a question on the test, because based on searching, this doesn't seem to be a common thing that anyone does.

jquery-extension not executing in chrome app

I've encountered a strange problem with my chrome app i'm developing at the moment.
I want to use the "knob" extension to use it for a alarm-clock slider (to set the time)
This wouldn't be a really difficult matter, wouldn't it be for the restrictions and strange issues found while programming a chrome app.
In my index.html file I included the jquery library and the knob extension. And that is where the problems started. Somehow, my scripts only can use the Id's of elements that are above them. So when I include the tags between the tags, nothing executes, if I put them after the first tags they only work with the things that are in this div container. thats why I put the script just before the tag. That works well for "normal" javascript usability. But because I have a that referes to a jquery function (for the knob) the jquery library should be already loaded before the function gets executed (if not, it just doesn't work). I tried to get a workaround by using these posibilities:
document.onload=test();
function test(){
$(function() {
$(".dial").knob();
});
}
document.onload=test();
$(function test() {
$(".dial").knob();
});
}
document.onload=$(function() {
$(".dial").knob();
});
}
well.... It didn't work. I also tried window.onload, with the same reuslt. does someone have a solution? It would be of great help.
Thank you,
neissen
Try like this:
$(function() { //document ready function
function test(){ //inside the ready function
$(".dial").knob();
}
test(); // and call the function here
});
Your Problems:
jQuery may not be loaded but you used some vanilla JS to handle jQuery, which will cause errors.
May be related to global and local.
For the external scripts, functions are only fired locally, which means the global object which contains the html won't be able to be accessed.
To make a global function and a jQuery library - JS:
if ("undefined" === typeof jQuery) {throw new Error("This library requires jQuery"); }
$(function() {
window.myFunction = function() {
doSomething();
}
doSomething();
})
Works calling from HTML - HTML:
<script>
$(function() {
doSomething();
})
</script>
Above is the safest way to approach a jQuery library. The $(function() {... part means exactly the same as $( document ).ready(function() {..., execute if loaded and ready, ensures the browser knows how to deal with all the functions used.

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

Hi I am having a "Uncaught ReferenceError: $ is not defined" while using bellow codes
I am currently getting the following error in my log. I have been looking at the samples in the framework and I just can't seem to find where the error is. It's been over a decade since I have done any HTML or js and what I did back then was very basic stuff. Any help would be appreciated
<script type="text/javascript">
var sQuery = '<?php echo $sQuery; ?>';
$(document).ready(function(){
if($('input[name=sPattern]').val() == sQuery) {
$('input[name=sPattern]').css('color', 'gray');
}
$('input[name=sPattern]').click(function(){
if($('input[name=sPattern]').val() == sQuery) {
$('input[name=sPattern]').val('');
$('input[name=sPattern]').css('color', '');
}
});
$('input[name=sPattern]').blur(function(){
if($('input[name=sPattern]').val() == '') {
$('input[name=sPattern]').val(sQuery);
$('input[name=sPattern]').css('color', 'gray');
}
});
$('input[name=sPattern]').keypress(function(){
$('input[name=sPattern]').css('background','');
})
});
function doSearch() {
if($('input[name=sPattern]').val() == sQuery){
return false;
}
if($('input[name=sPattern]').val().length < 3) {
$('input[name=sPattern]').css('background', '#FFC6C6');
return false;
}
return true;
}
</script>
It seems you don't import jquery. Those $ functions come with this non standard (but very useful) library.
Read the tutorial there : http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
It starts with how to import the library.
No need to use jQuery.noConflict and all
Try this instead:
// Replace line no. 87 (guessing from your chrome console) to the following
jQuery(document).ready(function($){
// All your code using $
});
If you still get error at line 87, like Uncaught reference error: jQuery is not defined, then you need to include jQuery file before using it, for which you can check the above answers
Put this code in the <head></head> tags:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
If you are sure jQuery is included try replacing $ with jQuery and try again.
Something like
jQuery(document).ready(function(){..
Still if you are getting error, you haven't included jQuery.
I know this is an old question, and most people have replied with good answers. But for reference and hopefully saving somebody else's time. Check if your function:
$(document).ready(function(){}
is being called after you have loaded the JQuery library
many other people answered your question above. This problen arises when your script don't find the jQuery script and if you are using other framework or cms then maybe there is a conflict between jQuery and other libraries.
In my case i used as following-
`
<script src="js_directory/jquery.1.7.min.js"></script>
<script>
jQuery.noConflict();
jQuery(document).ready(
function($){
//your other code here
});</script>
`
here might be some syntax error. Please forgive me because i'm writing from my cell phone. Thanks
Remember that you must first load jquery script and then the script js
<script type="text/javascript" src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="example.js"></script>
Html is read sequentially!
$ is a function provided by the jQuery library, it won't be available unless you have loaded the jQuery library.
You need to add jQuery (typically with a <script> element which can point at a local copy of the library or one hosted on a CDN). Make sure you are using a current and supported version: Many answers on this question recommend using 1.x or 2.x versions of jQuery which are no longer supported and have known security issues.
<script src="/path/to/jquery.js"></script>
Make sure you load jQuery before you run any script which depends on it.
The jQuery homepage will have a link to download the current version of the library (at the time of writing it is 3.5.1 but that may change by the time you read this).
Further down the page you will find a section on using jQuery with a CDN which links to a number of places that will host the library for you.
(NB: Some other libraries provide a $ function, and browsers have native $ variables which are only available in the Developer Tools Console, but this question isn't about those).

RequireJS and JavaScript API

I'm using a sample project from here.
Suppose I need to export some function from my module to provide some JavaScript API to the clients of my service.
But the declarations in my .js files are not visible outside RequireJS!
I add the following block to jquery-require-sample/webapp/app.html:
<script type="text/javascript">
$(document).ready(function() {
$('body').alpha().beta();
});
</script>
It fails: Uncaught TypeError: Object [object Object] has no method 'alpha'.
Is it possible to do what I want?
Based on the code you provided I'm assuming you added your code after the existing script tag in app.html. I think what you're seeing is a timing issue. After you load the page, take a look at the <head> tag and you should see script tags in the following order:
the "require" script
your new script
alpha
beta
so it's running your script before the alpha and beta are run. The reason is because require will process the first script, but not execute the "meat" of main.js until all it's dependencies are run (alpha and beta).
I hope this helps. The following changes to your code may also illustrate what's going on. the setTimeout gives alpha and beta a chance to load:
<script type="text/javascript">
setTimeout(function(){
$(document).ready(function() {
$('body').alpha().beta();
});
}, 5000);
</script>

Javascript error

I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!
<SCRIPT language=JavaScript>
<!--
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>
The error I am getting is when clicking on a drop down context menu on a page, for this line:
newImage("\/_layouts\/images\/icon1.gif");
The object doesn't accept this property or method
Code: 0
I really don't see what could happen... Any tips on what may be happening here?
Have you tried loading your scripts into a JS debugger such as Aptana or Firefox plugin like Firebug?
Why are you escaping the forward slashes. That's not necessary. The two lines should be:
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
It is hard to answer your question with the limited information provided:
You are not showing the complete script
You never said what the exact error message is, or even what browser is giving the error.
Which line number is the error supposedly coming from?
I'd recommend using Firebug in firefox for debugging javascript if you aren't already. IE tends to give bogus line numbers.
And as others have already said, the language attribute for script tags is deprecated.
Write proper xml with the " around attributes.
<script type="text/javascript">
function newImage(arg) {
var rslt = new Image();
rslt.src = arg;
return rslt;
}
function changeImages(a, b) {
a.src = b;
}
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
</script>
should your script block not be:
<script type="text/javascript">
?
For starters, start your script block with
<script type="text/javascript">
Not
<script language=JavaScript>
That's probably not the root of your problem, but since we can't see your script, that's about all we can offer.
You probably need to enlist the help of a Javascript debugger. I've never figured out how to make the various debuggers for IE work, so I can't help you if you're using IE.
If you're using Firefox or you CAN use Firefox, make sure you have a Tools / Javascript Debugger command. (If you don't, reinstall it and be sure to enable that option.) Next, open up the debugger, rerun the problem page, and see what comes up.
How are you calling changeImages? It looks as though you are not saving a reference to the images returned by newImage. You probably want to save the results of newImage and pass that to the changeImages routine. Then changeImages should look like this:
function changeImages(a, b) {
a.src = b.src;
}
You also may want to ensure that the images have finished loading before calling changeImages.
You've posted the routine that throws the error, without posting the error or showing us how you are calling it. If none of the answers posted fix your problem then please post some detail about how you are calling the method, which specific line the error is on, and what the error message is.
You firebug to debug.
http://www.mozilla.com/en-US/products/download.html?product=firefox-3.0.10&os=win&lang=en-US
https://addons.mozilla.org/en-US/firefox/addon/1843
JSLint is also a nice resource.
http://www.jslint.com/
Using CDATA instead of the <!-- // -->
http://www.w3schools.com/XML/xml_cdata.asp
<script type="text/javascript">
<![CDATA[
]]>
</script>

Categories