2

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?

janfoeh
  • 10,243
  • 2
  • 31
  • 56

1 Answers1

1

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>
Shef
  • 44,808
  • 15
  • 79
  • 90
  • Thanks! Unfortunately, the script tag in question will not always be the last one in the DOM tree. I would need the last element inserted, not the last in terms of position. – janfoeh Jul 12 '11 at 14:36
  • 1
    additionally, pages loaded using $.ajax() will run the scripts in them but discard them such that they're not available via $('script') - so this solution will fail in such cases too (see my post: http://stackoverflow.com/questions/8234215/where-are-scripts-loaded-after-an-ajax-call) – ekkis Nov 22 '11 at 23:32