2011-11-07 59 views
1

我有這樣的:添加src屬性<script>

script_url = 'http://externaldomain.com/script.js' 
div_id = 'div'+Math.floor(Math.random() * 1000000); 
document.write('<div id="'+div_id+'"><scr'+'ipt id="banner-to-load"></scr'+'ipt></div>') 

DOM準備就緒後我這樣做:

$('#banner-to-load').attr('src',script_url) 

現在,script_url追加,但沒有任何反應。外部腳本有一些功能,但它們不起作用。我如何運行外部腳本?或者如果我運行它document.write裏面會重建我已編譯的DOM?

+2

看看*或者如果我運行'document.write'內將重建我已經編譯DOM?*是的。 –

+0

您是否試過'$('#banner-to-load')。prop('src',script_url);'? –

回答

1

嘗試在添加src之前設置src並重新檢查您的script_url。

document.write('<div id="'+div_id+'"><script ' 
    +'id="banner-to-load" src="' + script_url + '"></scr'+'ipt></div>') 

更新:或進行跨域的Ajax查詢。如果您控制其他頁面,則可以通過設置「Access-Control-Allow-Origin」標題來允許跨域查詢。

+0

您也可以使用雅虎代理進行跨域查詢:http://developer.yahoo.com/javascript/howto-proxy.html – PiTheNumber

+0

我無法更改標頭 – rsboarder

+0

因此請使用Yahoo代理。 – PiTheNumber

1

嘗試將banner_to_load追加到src屬性是不是異步加載body對象

2

。使用Ajax加載JS

$.getScript(); or $.ajax({url:source, dataType: "script"}); 

這裏 http://api.jquery.com/jQuery.getScript/

+0

我有跨域 – rsboarder

+0

是的,這是一個常見問題。製作一個PHP腳本作爲跨域腳本代理並通過ajax加載它 – John

+0

跨域是沒有問題的。我一直這樣做。看到我的答案。 – PiTheNumber