We have introduced two different methods for embedding JavaScript Functions into ASP. NET pages. What is the difference between them? The main difference is that,
RegisterstartupscriptThe method is to embed Javascript into the bottom of the ASP. NET page, which is exactly at the end of the element.
</Form>.
RegisterclientscriptblockThe method is to embed Javascript into the page to enable elements.
<Form>. So what's the difference? As we will see, this is a big difference.
Here is an example. Here is how to focus on a text box on the page when the page is loaded to the browser-UseRegisterstartupscriptVisual Basic of the method:
Page. clientscript. registerstartupscript (Me. GetType (), "testing ",_
"Document. Forms [0] ['textbox1']. Focus ();", true)
When the browser runs at the bottom of the page and executes this small JavaScript code, a text box on the page is generated and placed on the page. Therefore, this method runs normally. However, if you do not follow the above method, write the following code (UseRegisterclientscriptblockMethod): page. clientscript. registerclientscriptblock (Me. GetType (), "testing ",_
"Document. Forms [0] ['textbox1']. Focus ();", true)
The text box control will not get the focus, and a javascript error will be generated on the page.
The error occurs because the browser encounters JavaScript before the text box appears on the page. Therefore, JavaScript cannot be found.Textbox1.
Place Javascript in a separate file (. JS)
We strongly recommend that you place JavaScript Functions in a separate file (. js file ). Once they are in a separate file and are part of a project, you can use some methods you have introduced to import the file to the page.
For example, you can use the following code to include a. js file to an ASP. NET page:
Visual Basic
Page. clientscript. registerclientscriptblock (Me. GetType (), "myscript ",_
"Myjavascriptfile. js ")
C # page. clientscript. registerclientscriptblock (this. GetType (), "myscript ",
"Myjavascriptfile. js ");
Once the. js file is imported to the ASP. NET page, you can call any JavaScript function as before. This is a good method to manage JavaScript Functions and logically separate them from other ASP. NET pages. You can also use this method to easily use the same JavaScript function in multiple ASP. NET pages.