Tristan
Tristan

Reputation: 6906

jQuery append doesn't work fully with <script> tag

Appending a script element using jquery rather than putting it in the html by hand seems to lead to very different results. For instance

snaphtml = '<script src="http:\/\/seadragon.com\/embed\/lxe.js?width=auto&height=400px"><\/script>';
$('#content').append(snaphtml);

destroys the layout of my page, but putting the script element in the page directly works fine.

I have posted a test case online:

The second div should not be deleted / invisible once the silverlight object is added.

Ideas?

Upvotes: 2

Views: 1051

Answers (4)

Doug Neiner
Doug Neiner

Reputation: 66191

Tristan, you will not be able to include the script you reference dynamically onto the page after it has finished loading. The external script is using document.write which will only work correctly when called before the page has finished loading. This is why your static implementation works fine, and your dynamic one tears the page apart.

You might want to put together a dummy HTML file that just has a basic HTML structure and this script in it already. Then dynamically add an iframe to your page that loads the HTML. There are even more dynamic ways to make it work with an iframe, but that would be the easiest.

Upvotes: 2

eringen
eringen

Reputation: 381

try to break script tag like snaphtml = '</sc'+'ript>'

Upvotes: 1

Kobi
Kobi

Reputation: 138017

Try to use $.getScript:

$.getScript("http://seadragon.com/embed/lxe.js?width=auto&height=400px");

Edit: The provided script is using document.write, which is likely causing your problems: you cannot add it dynamically at the middle of the page. Try loading SeaDragon as shown here:
http://www.seadragon.com/developer/ajax/getting-started/

Upvotes: 1

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827396

I would recommend you to use $.getScript method for loading external script files programmatically:

$.getScript('path/to/script.js', function() {
  alert('Script loaded.');
});

The script load is made asynchronously, and as you see in the above example, you can specify a callback function that will be executed when your external file has been loaded and is ready to use.

Upvotes: 3

Related Questions