Question

I have a simple html page with a div. I am using jQuery to load the contents of an aspx app into the "content" div. Code looks like this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
    </script>
    <script type="text/javascript">
        jQuery.noConflict();
    </script>
</head>
<body>
    <div id="content">
        <div id="loading"> 
            <div class="loading-indicator">Loading...</div>
        </div>
    </div>
</body>
<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery("#content").load("default.aspx");
    });
</script>
</html>

The problem is default.aspx uses shadowbox and other javascript libraries. When that code tries to execute on default.aspx it acts like the js source files were not loaded. I check in firebug and the js files are there (no 404 or anything). Anyone know what I'm missing? As you can see I used the jQuery noConflict function because I thought the use of $ might be conflicting with the other libraries but no help there...

Was it helpful?

Solution

Is the code that is not executing rendered out as script blocks, I understand the libraries loaded but any script blocks or inline javascript will not execute when loaded dynamically like that. You have to come up witha solution that will evaluate the script blocks returned for any of it to be valid. I'll see if I can dig an example from prototype, I remember them having one.

UPDATE:

This is straight from prototype...

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>'

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  }

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  }

Of course you can simplify that for your needs, but when a page is returned dynamically you have to manually evaluate all scripts as the browser will not evaluate script injected into the element automagically.

OTHER TIPS

I have code doing this, it might be more verbose than is needed, but nested js files shouldn't be a problem.

jQuery.get('default.aspx', null, function(data) {
    $('#default').append(data);
}, 'html');

Seems like a common problem: http://andreineculau.wordpress.com/2006/09/29/ajax-ondemand-javascript-or-dynamic-script-tags/

I'm guessing it's security built into browsers to prevent an ajax response from running arbitrary script.

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