Question

See this demo from Filament Group using their Progressive Enhancement enhance.js library

Modifying to give :-

<script type="text/javascript" src="../_shared/EnhanceJS/enhance.js"></script>
<script type="text/javascript"> 
// Run capabilities test
enhance({
loadScripts: [
 {src: 'js/excanvas.js', iecondition: 'all'},
 '../_shared/jquery.min.js',
 'js/visualize.jQuery.js',
 'js/example.js'
],
loadStyles: [
'css/visualize.css',
'css/visualize-dark.css'
] 
}); 

    alert($);

</script> 

I get an "$ is undefined error" on the alert presumably because jQuery has not loaded yet.

Note - the alert($) is just for debugging - I am trying to do something with that e.g. $('some-selector') - and no $(handler) or $(document).ready etc don't work either - jquery is not loaded, $ is not defined.

enhance's onScriptLoaded looks like it should do he trick but if I add in

onScriptsLoaded:[runMyCode()]

and later

function runMyCode()
{
    alert("runMyCode was called");
    alert($);
}

The first alert works but $ is still not defined.

If I call runMyCode on a click event of a button it does work.

So the question is - how can you run code once all scripts have finished loading with enhance.js?

P.S. Same problem verified in IE8/FF3/Chrome7

Was it helpful?

Solution

I think this is what you're after, note that onScriptsLoaded is used directly as a callback, so it should be a function, not an array:

enhance({
   loadScripts: [
    {src: 'js/excanvas.js', iecondition: 'all'},
    '../_shared/jquery.min.js',
    'js/visualize.jQuery.js',
    'js/example.js'
   ],
   loadStyles: [
    'css/visualize.css',
    'css/visualize-dark.css'
   ],
   onScriptsLoaded: function() { alert($); }
});

Or more generally for a function, pass just the reference like this:

   onScriptsLoaded: runMyCode

The reason onScriptsLoaded:[runMyCode()] "kind of" works is it's immediately invoking the runMyCode function (at the time this line runs, not when the scripts finish) and makes an array from that result. This will actually throw an error when scripts do finish, since onScriptsLoaded is expected to be a callback function, not an array.

OTHER TIPS

I think this may be a problem:

onScriptsLoaded:[runMyCode()]

have you tried (assuming the array notation is correct): (edit — it is not correct)

onScriptsLoaded: [runMyCode]

? The first way, you're calling your function at the time you're setting up the library. You want to pass just the reference to your function instead.

edit actually it should just be:

onScriptsLoaded: runMyCode

I don't know where the array came from; it's definitely not mentioned in the "enhance.js" documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top