I have a simple class to append a content.html file when MyClass.display() is called.
class MyClass
@display: (display) ->
$.get 'content.html', (data) ->
$('body').append data
The code above always append the data to the end of the body.
The HTML code is simply this
<html>
<head></head>
<body>
<p>text before</p>
<script src="file.js" type="text/javascript"></script>
<script type="text/javascript">
MyClass.display();
</script>
<p>text after</p>
</body>
</html>
I’m wondering how it is possible to append the data just after the enclosing </script> tag that triggered the function. That would in between the </script> and the following <p> tag.
One requirement is that I should not modify the HTML markup. I can not add IDs directly to markup as proposed in one of the answers below.
I know this is possible because I can see it in the Google AdSense code. But since their javascript code seems encrypted I can’t decode how its done.
Any idea how to achieve this?
While javascript code is running, its containing script tag is the last element available in the DOM object
You can grab its reference for example like this,
From there, depending on the content of
content.htmlyou can do the necessary work to place content after the script tag (not append inside the script tag, that’ll not be what you’re looking for)e.g. If
content.htmlhas its own top level element,pthen you can simply
note 1: you must get reference
eleoutside of the$.getcallback. the callback runs asynchronously – by then the DOM would’ve likely loaded more elements andscript:lastmay not be your script tag anymore.note 2: if
content.htmldoes not contain a top level element that wraps the entire thing, then you’d have to wrap it yourself in the callback, e.g.ele.after("<div class='my-own-wrapper'>" + data + "</div>");For reference: https://gist.github.com/4122339