Note that there are some explanatory texts on larger screens.

plurals
  1. POLoading javascript asynchronously - How to do callbacks?
    primarykey
    data
    text
    <p>I am building a javascript widget that should load asynchronously.</p> <p>Problem is that there can be more than 1 of these widgets on the page and that the widget should be initialized by sending it an option array via {}.</p> <p>What is the best way to accomplish this? I heard that simply setting onload or onreadystatechange does not work in all browsers. </p> <p>I've checked out the digg widget, but I can't really comprehend what they're doing, could anyone take a look at that? </p> <p>Here's some of their code:</p> <pre><code>(function () { var s, s1, diggWidget = { id: "digg-widget-1282651415272", width: 300, display: "tabbed" }; if (window.DiggWidget) { if (typeof DiggWidget == 'function') { new DiggWidget(diggWidget); } else { DiggWidget.push(diggWidget); } } else { DiggWidget = [diggWidget]; s = document.createElement('SCRIPT'); s.type = 'text/javascript'; s.async = true; s.src = 'http://widgets.digg.com/widgets.js'; s1 = document.getElementsByTagName('SCRIPT')[0]; s1.parentNode.insertBefore(s, s1); } })(); </code></pre> <p>So, if the DiggWidget is already available (loaded earlier due to multiple instances), it makes a new widget if DiggWidget is a function, otherwise DiggWidget is used as an array and the current settings are pushed to it. </p> <p>First, why would DiggWidget ever be a function?</p> <p>If the widget is the only one (or first), the script tag is added asynchronously, no callbacks are defined.</p> <p>Then, looking at widgets.js they do this:</p> <p>At the top: </p> <pre><code>(function () { var A; if (window.DiggWidget) { if (typeof DiggWidget != "function") { A = DiggWidget } else { return } } </code></pre> <p>At the bottom: </p> <pre><code> if (A) { while (A.length) { new DiggWidget(A.shift()) } } </code></pre> <p>Now I don't quite understand this. Is DiggWidget (the array) available to that .js ? It's in a anonymous function. So if I include such a script twice, wouldn't DiggWidget be a new instance every time? </p> <p>Or am I completely in the wrong on this? Sorry if so. If there's any better methods to have a callback with multiple instances of the script, please do tell.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload