Home  >  Article  >  Backend Development  >  The difference between RegisterClientScriptBlock and RegisterStartupScript

The difference between RegisterClientScriptBlock and RegisterStartupScript

巴扎黑
巴扎黑Original
2016-12-19 16:40:221619browse

RegisterClientScriptBlock and RegisterStartupScript both register a script block.

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

The difference between them is that RegisterClientScriptBlock is registered at the front of the body, while RegisterStartupScript is registered at the end of the body.

Why is this? Some performance optimization articles say that the script should be loaded in the body last. However, according to the actual situation of some applications, the script must be loaded initially. In this case, ClientScript.RegisterStartupScript must be used.

Let’s talk about their second parameter key.

The second parameter key is used to avoid repeated registration. In the above code, their keys are all script1, but there will be no conflict because the method names are different.

The following codes are all RegisterStartupScript. The second sentence will not have any output because a script1 script has been registered before.

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

Although Response.Write can output JavaScript, the output content is in < html> Previously, this would cause problems such as stylesheet failure and even errors in some fragile browsers.

ClientScript can easily manage JavaScript. It should be said that there is only one difference between ClientScript.RegisterClientScriptBlock and ClientScript.RegisterStartupScript, that is, RegisterClientScriptBlock writes the script code after

, while RegisterStartupScript writes the code after
(note the closing tag) before.

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

It can be seen that the syntax of the two is the same.

type The type of startup script to be registered.

key The key of the startup script to be registered, which is the name you give this script. Scripts with the same key are regarded as duplicates. For such scripts, only the first registered one is output. The same keys in ClientScriptBlock and StartupScript are not considered duplicates.

script script code.

addScriptTags Whether to add the