Javascript : Execute code after a self executing anonymous function is loaded - javascript

I have a script "selfexec.js" which does few things:
!function(){ A = {init : init}}()
I basically use this script as a plugin that can be loaded from other sites.
So, from Site B, I load this function and then want to call the method A.init but A is always coming out as undefined as its getting executed even before the anonymous function is loaded.
I tried to attach it to the window but still no luck
Anyone has better approach of doing this? Any help would be appreciated

it seems like the issue is that you are trying to use A variable before it was initialized by 3rd party script. So the order is matter here: load 3rd party script before and start use it after. Also I personally like an approach with putting calls to the queue (similar approach is used even for google analitics). read about it more here
https://coderwall.com/p/2wmqhw/load-3rd-party-js-asynchronously-initialize-queue-replace-queue
so, you will need to define a way how your client should load code from your site and all methods will 100% be executed after 3rd party code was loaded and initialized.

Related

ExternalInterface addCallback repeatedly fails

I'm trying to get JS in a Wordpress webpage and an Actionscript 2 Flash movie to talk to one another. The attempt is failing miserably. On every attempt to call the function that I've set a callback for, I get "..... is not a function" in the browser error console (I'm using Firefox 20).
Here's how things are set up:
The page is a bit unusual, being a Wordpress page with inline javascript. The main javascript is a jQuery.ready() block of code that loads the flash object (this is done so that GET parameters in the URL can be passed into the flash). Once it's loaded, there's a link with this:
Region A
Meanwhile, the flash object has this in it to make it possible:
import flash.external.ExternalInterface;
System.security.allowDomain("thisdomain.com"); // the domain on which the flash is hosted
ExternalInterface.addCallback("setRegion", null, switchZone); //switchZone is the function's internal name
The flash's container has allowScriptAccess set to "always", and I can confirm that the jQuery statement is hitting the right target. However, when the flash object is debugged, the addCallback returns false— a sign that it's failed. Anyone have any ideas what could be going on?
I met this kind of problem before. To explain this, you may just image your flash file to be a image. Usually, the image in you page will show after the whole page is loaded. For your flash file, in $.ready event, the flash DOM is inserted into your page, but the content of it is loading and the environment of it is not ready yet.
To handle this, you need to register a callback function in your page like this:
window.ping = function () {
$('#fmap')[0].setRegion('regiona');
}
Then in your flash environment, call the ping() registered.
The order of function call is the key point here.
OK, figured it out. First off, the function declaration needed to be above the ExternalInterface.addCallback bit. In addition, once that was done it started throwing a different error, so I had to make a new function... thanks for your help.

$(window).load fires too quickly in IE with asynchronous js libs

I have some serious problem with getting asynchronously some js libs and executing them in $(window).load in IE
all works in other browsers of course
so the problem is, that I'm doing something like
<script type="text/javascript">
var scr1 = document.createElement('script');
scr1.type = 'text/javascript';
scr1.src = 'some_lib.js';
$('BODY').prepend(scr1);
</script>
Just before </body> and use $(window).load method in html above it to operate on some plugins in some_lib.js, but it all happens to fast in IE, probable because of that asynchronous lib including, and I get an error, that method is not available for the element.
Is there any chance of maybe modyfying $(window).load method so I still could use it in the same way for every browser ?
Any code that you have in the window.load() call must be placed in a function (called onLoad in this example).
Every time you have a script that you dynamically load, increment a counter. Also include something to decrement that counter...
src1.onload = function() { counter--; onLoad(); }
Then in 'onLoad' have the first line...
if (counter > 0) return;
That means that onLoad will fire at window.load and after every script is loaded, but will only execute when it's all loaded.
It's scrappy, but it will solve your problem.
You haven't really described the reason you need to load these libraries asynchronously. Third party libraries often have "on script load" functionality that you can define before the script is loaded. If you need to load multiple libraries before you can execute your code, you may have to either 1. fire up some code every time a library is loaded to test to see if all libraries required are loaded and then fire off you code 2. for every library, create a jQuery promise/deferred to get resolved when that library is loaded and use $.when(promises).done(function/code) to test and run the code whenever a particular set is loaded, or 3. rewrite to use RequireJS. If these libraries are YOUR code, well, you may have to add start up code to your libraries anyway; It might be a good time to learn RequireJS.
I wish I could recommend further, but learning the basics behind RequireJS has always been on my todo list, but it hasn't been done; I just know of people here successfully using it. If that seems like too much trouble, I'd consider some variant of option 2. If you don't know what jQuery would be used eh... you may be stuck with option 1 or 3.
Edit:
Of course, that's not to say that jQuery has got the only promise library, I just often recommend using promises in some form for these kind of things..
Archer's technique looks interesting, I just don't know how reliable it is (it might be quite reliable, I just would like to see proof/documentation). You could combine that with option 2 also, quite well, if you want to short-cut execution for some things while leaving others to be dealt asynchronously and if those script onload methods really work as expected.

Identify which Javascript executed a call using Firebug or Google Chome

How to know which Javascript (.js) executed a GET or Ajax call using Firebug or Google Chrome Plugin?
For example, a request for a image or html file executed by a Javascript, how to know which Javascript on the page executed that
Update:
I have to (shamefully) admit that the original below was wrong. Due to the nature of the js execution flow this works at the first execution time:
console.log($("script").last().attr("class")); //or whatever
That, however, is not good enough, as illustrated by a call on a timeout. We need to keep the reference to the script element, this can be achieved by wrapping script contents into a closure and creating a variable to store the jQuery reference:
(function(){
var $scriptElement = $("script").last();
console.log($scriptElement.attr("class")); //or whatever
})();
Now, I have to disclaim that with the markup as above it is unlikely to be practical unless you come up with a better way to store the script element reference... this pretty much became a rather bad example of what could be done but really shouldn't :(
Unless you have to get the reference in-code, you would be much better off looking at the console output, it actually tells you where the output originated from, with the line# and everything:
Original:
Not sure how applicable this would be to external js (script tag with a src), but for inline scripts you could do something like this w/jQuery:
$(this).closest("script");//gets you reference to the script element
I'm assuming it would just a matter of getting its src attribute! Let us know if it works.
console.log($(this).closest("script").attr("src"));
In chrome you can break on any xhr request. This will only set breakpoints for AJAX calls though.

What's with the random Javascript errors?

I'm developing a site in javascript and jquery. Sometimes when I refresh I just get different random errors in firebug. What's the deal?
edit: I'm getting errors like a variable isn't defined, when clearly it is and working, and when i refresh again, the error is gone..
using Firefox V3.5.5 Firebug V.1.5.3 and I'm primarily working with jQuery 1.4.2
OK. While it's more or less impossible to give a reasonable solution to such a general question, I'll just add my 2 cents' worth:
One possible source of "undefined variable" errors comes from including several scripts, which may or may not always load and execute in the same order. If you define a variable in one script (let's call that script declare.js) and use it in another (let's say use.js), and use.js is executed before declare.js, then you will get such an error. If the scripts execute the other way around, everything will appear fine.
If you're interested in this very topic, have a look at e.g. Steve Souders' book Even faster web sites, published by O'Reilly. More specifically, look at the chapter about non-blocking script loading.
Most common cause is that you're trying to execute Javascript before the DOM is loaded and thus before all HTML elements are available in the DOM tree, which in turn may cause that simple calls like document.getElementById(id) and jQuery's $(selector) may return undefined elements. That it sometimes works is pure coincidence and a matter of timing.
You need to ensure that any Javascript/jQuery code which is supposed to be executed during page load and relies on the availability of the elements in the DOM tree, also really get executed after the DOM is loaded. In plain vanilla JS you can do so:
window.onload = function() {
document.getElementById(someId);
}
and in jQuery:
$(document).ready(function() {
$(someSelector);
});

Calling a flash external interface AS3 function on page load

I have a function defined in AS3 that's gonna be called from client side via JavaScript. The AS3 functions simply print some value on SWF screen when it's called.
It works fine when I set an onclick event handler to a button and call the AS3 function. However I want to call this AS3 function as soon as the page loads. I am using jQuery in the project and I placed the call to the AS3 function inside $(document).ready(), but that gives me the following error in FF2 firebug:
getFlashMovie("my_movie_name").my_as3_function is not a function
Then, I tried calling the by setting an onLoad event handler on the , but that also does not work - produces the same error.
So, my question is, how do I call an AS3 function automatically once page loads? In my project, I need to pass some client side initialization information to the flash once page loads.
You'll need to have your flash call a function in the page to notify it that the Flash is loaded and initialized, then use that as your entrypoint.
In the flash:
ExternalInterface.call('flashReady');
In the page:
<script>
function flashReady() {
..
}
</script>
If you use swfObject to embed your SWF (probably a good idea anyway) then you can use its addDomLoadEvent() function which allows you to do something once the SWF is fully loaded
swfobject.addDomLoadEvent(function() {
$("#swfobject").get(0).inited('you are loaded!');
});
i am not trying to be a wiseguy here but do you test your work on a server?
external interface, addcallback dose not work on local filesystem, and eventually you may have to add:
flash.system.Security.allowDomain('http://localhost');
if you are running on local.
:P
The problem is that the Flash object is not initialized yet when the page finishes loading. It would probably be much safer to perform this initialization from within AS3. If you want to pass values from the HTML page, use flashVars.
I ran into this problem myself a couple of weeks ago. The solution is pretty simple :)
First, you need to put in your DOM a div
<div id="timewriter"><div>
You'll also be using the jQuery Timers plugin to time your loading. After this preparation the things will go very easy.
The following piece of code will go in your $(document).ready();
var movie = getFlashMovie('my_movie_name');
if(movie.PercentLoaded() != 100)
{
$("#timewriter").everyTime(100, function ()
{
if(movie.PercentLoaded() == 100)
{
$("#timewriter").stopTime();
//the movie is loaded, call here your functions; usually this happens if you don't use cache
}
});
}
else
{
//the movie is loaded, call here your functions; usually you get here if you use cache
}
Later edit: be careful that HTML page load doesn't mean the swf was loaded, that happens right after the web page load complete event. Also my solution is based on jQuery javascript library.
Answers by both tweakt and Bogdan are viable. Use tweakt's method if you have access to the Actionscript. Use Bogdan's if you don't. I was looking for an alternative besides polling (when you don't have access to the Actionscript) but I have been unsuccessful in finding one thus far. Events are mentioned here: http://www.adobe.com/support/flash/publishexport/scriptingwithflash/scriptingwithflash_03.html But noone seems to know how to use them.
For the sake of completion, you would also have to use import flash.external.*; to make everything work.
It seems like the collection of answers offered answers this closest to it's entirety.
As David Hanak said, the flash object cannot be accessed yet because it is initializing, though i disagree that we must rely on flashvars, though I love them.
Tweakt is right, but upon calling the function in the javascript, have that call the javascript function that calls back to your swf; This way we know flash is ready as it sent the first call.

Categories