janfoeh
janfoeh

Reputation: 10328

Executing <scripts> loaded via .ajax in a specific context

I have a page A with several containers, into each which I load the content of page B. Page B consists of some HTML and Javascript in <script> tags.

I now need to configure the JS embedded in page B — let it know the DOM node it has been loaded into.

Server-side processing with URL parameters etc. is not an option unfortunately.

A simplified example - page A:

<div id="container1"></div>
<div id="container2"></div>

<script type="text/javascript">
  $('#container1').load('pageB.html');
  $('#container2').load('pageB.html');
</script>

Page B:

<p>Lorem ipsum</p>
<script type="text/javascript">
  (function(){
    alert('I have been embedded into container #???');
  })();
</script>

I see two basic ways of achieving this:

  1. pass the information in from page A into page B
  2. have the script in page B figure out its position itself

For 1.: is there a way to execute embedded JS loaded via AJAX in a specific binding / change the scope of this within page B?

For 2.: is there a cross-browser way to get a reference to the currently executing <script> node? Something like Geckos document.currentScript?

Upvotes: 2

Views: 694

Answers (1)

Shef
Shef

Reputation: 45589

Try:

<p>Lorem ipsum</p>
<script type="text/javascript">
    (function($){
      var $container = $('script:last').parent();
      alert('I have been embedded into container #'+$container.attr('id'));
    })(jQuery);
</script>

Upvotes: 1

Related Questions