Ways to deal with dynamic javascript whose content depends on user inputs
<p>I am working on integrating <a href="http://deepliquid.com/content/Jcrop.html" rel="nofollow">Jcrop</a> into my web app. Jcrop has a javascript function whose content uses the dimensions of the picture uploaded by user and thus the javascript is dynamic. I  have some vague idea on the approaches that I can take but not knowing how.</p>

<p>The sequence of events in this scenario goes like this:</p>

<ol>
<li>User chooses a picture to upload</li>
<li>A popup shows up (ie. AJAX) to give the user the ability to crop the picture. This is done by the use of Jcrop, which requires the javascript below.</li>
</ol>

<p>Javascript code:</p>

<pre><code>function initCropping(width, height, preview_width, preview_height) {
var jcrop = $.Jcrop('#cropbox', {
    onChange: showPreview,
    onSelect: showPreview,
    aspectRatio: 1,
    minSize: [preview_width, preview_height]
});

$('#crop').filter(':button').click( function () {
    var selection = jcrop.tellSelect();
    alert(selection.x + ', ' + selection.x2 + ', ' + selection.y + ', ' + selection.y2);
});

// Our simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showPreview(coords)
{
    if (parseInt(coords.w) &gt; 0)
    {
        var rx = {{ preview_width }} / coords.w;
        var ry = {{ preview_height }} / coords.h;

        $('#preview').css({
            width: Math.round(rx * {{ width} }) + 'px',
            height: Math.round(ry * {{ height }}) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
    }
};
};
</code></pre>

<p>The problem here is that {{ width }} and {{ height }} are the dimensions of the uploaded picture, so they can't be determined until after Step 1 and thus I call the javascript dynamic.</p>

<p>The approaches that I have vague idea are:</p>

<ol>
<li>Serve that javascript from my web server</li>
<li>AJAXly send the picture dimensions to the client browser and build that dynamic javascript function at the client end by another javascript function.</li>
<li>Some other approaches??</li>
</ol>

<p>Please share the approach that you would take in this scenario, how (an example would be great), and why. Thanks.</p>

<p>FYI. I am using Django and jQuery.</p>
