Andreas
Andreas

Reputation: 3374

Placing script tag in div and execute

I'm building a small advertisement system for my website so that I can just add new ads in the database. Most ads consists of images and I will just write an image as innerhtml to a div. This works fine. However, some ads consists of a script tag only that should be placed where the ad is wanted. Since I have to do this dynamically from either code behind in .NET or from an ajax call, I have some problems with this. Just setting a innerhtml of a div like this:

<div id="asdf" runat="server">
    <script type="text/javascript" src="xxxxx"></script>
</div>

... won't work since it won't get executed. No matter if i set it in the code behind on page load, or set with an ajax call.

I might be able to call eval() somehow, but this doesn't guarantee the script will be placed exactly where i want it to be if I got it right.

Any ideas? This can't be a new problem, many advertising networks has script tags instead of images and such.

Edit: The javascript file is located on another domain. Everything works if i set the src attribute to a local file containing only an alert! Can't you make this happen across domains?

Upvotes: 1

Views: 715

Answers (2)

Mohit Pandey
Mohit Pandey

Reputation: 3813

You can try this:

var script = document.createElement('script');
script.src = 'xxxxxx';
script.type = 'text/javascript';
var div = document.getElementById('asdf');
div.appendChild(script);

Upvotes: 1

SHANK
SHANK

Reputation: 2958

you can add script tags dynamically, if you know from which source you want to add a file, like this:

    // Get head object from DOM.
var head_obj = document.getElementsByTagName('HEAD').item(0);

// Create script object.
var script_obj  = document.createElement( 'script' );
script_obj.type = 'text/javascript';
script_obj.src  = File_Path;

// Define functions to be called on script load and load body.
script_obj.onload = onLoadFunc;

// Appendnd script object to the head object.
head_obj.appendChild( script_obj );

Hope that helps

Upvotes: 0

Related Questions