首頁  >  文章  >  後端開發  >  RegisterClientScriptBlock與RegisterStartupScript的差別

RegisterClientScriptBlock與RegisterStartupScript的差別

巴扎黑
巴扎黑原創
2016-12-19 16:40:221563瀏覽

RegisterClientScriptBlock、RegisterStartupScript 都是註冊一個腳本區塊。

ClientScript.RegisterClientScriptBlock(this.GetType(), "script1", "alert(1);", true);
ClientScript.RegisterStartupScript(this.GetType(), "script1", "alert(2);", true);

它們的差別就是RegisterClientScriptBlock 是註冊在body 最前面,而RegisterStartupScript 是註冊在body 最後面。

為什麼這樣呢?一些優化效能的文章說,script 要放在 body 最後加載,但根據一些應用的實際情況,必須得在最初加載 script,這時就得用 ClientScript.RegisterStartupScript 了。

說說他們的第二個參數 key。

第二個參數 key 是用來避免重複註冊的,上面程式碼,他們的 key 都是 script1,但不會衝突,因為方法名稱都不相同。

下面程式碼都是 RegisterStartupScript,第二句就不會有任何輸出,因為之前已經註冊過一個 script1 的腳本了。

ClientScript.RegisterStartupScript(this.GetType(), "script1", "alert(2);", true);
ClientScript.RegisterStartupScript(this.GetType(), "script1", "alert(3);", true);
ClientScript.RegisterStartupScript(this.GetType(), "script2", "alert(4);", true);

 

雖然,Response.Write 可以輸出JavaScript,但輸出的內容是在 之前,這會導致一些問題,例如樣式表失效,甚至會導致一些脆弱的瀏覽器發生錯誤。

 

ClientScript 則可以方便地管理JavaScript,應該說ClientScript.RegisterClientScriptBlock 與ClientScript.RegisterStartupScript 只有一點區別,那就是RegisterClientScriptBlock 將腳本程式碼寫在

之後,而RegisterStartupScript(RegisterStartupScript 將程式碼寫在
是結束標籤)之前。

public void RegisterClientScriptBlock(Type type, string key, string script)
public void RegisterClientScriptBlock(Type type, string key, string script, bool addScriptTags)
public void Regoid,stroids (Type type, string key, string script, bool addScriptTags)

可以看出二者語法相同。

type 要註冊的啟動腳本的類型。

key 要註冊的啟動腳本的鍵,也就是你自己給這段腳本取的名字。相同 key 的腳本被當作是重複的,對於這樣的腳本只輸出最先註冊的,ClientScriptBlock 和 StartupScript 中的 key 相同不算是重複的。

script 腳本程式碼。

addScriptTags 是否新增 <script> 標籤,如果腳本程式碼中不含 <script> 標籤,則應指定該值為 true,若不指定該值,則會被當作 false 對待。 <p>ClientScript.RegisterClientScriptBlock(this.GetType(), "key1", @"function Go()<p>{<br/>alert('');<br/>}", true);<br/>ClientScript.RegisterStartupScript(this.GetType() ""true); key1", "Go();", true);<br/><p><br/></script>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
上一篇:C#檔案操作下一篇:C#檔案操作