asp.net placeholder in the head of a page
I have a page that includes javascript which I only want to run under certain conditions. To do this I have placed the scripts into an asp:placeholder
This actually seems to work but when I run a debug on the page I get the following warning.
Element 'placeholder' is not a known element. This can occur if there is a compilation error in the Web site, or the开发者_StackOverflow社区 web.config file is missing.
If I move the placeholders into the body of the page the warning goes, but that means I'm left with scripts in the body which I also want to avoid. Does anyone have any hints on the best practice for this scenario?? thanks
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='scripts/pageLoadAnimations.js'></scr" & "ipt>"
me.Header.Controls.Add(lt)
End Sub
You can include JS file straight from code behind:
If (some condition is true) Then
Page.ClientScript.RegisterClientScriptInclude("jQuery", "jquery-version.js")
End If
A couple of ways which fit your needs are:
Firstly, you could change your <head>
tag to <head id="header" runat="server">
then this allows you to dynamically add anything into it, e.g.
dim lt as new Literal()
lt.text = "<script type='text/javascript' src='pathtojavascriptfile'></script>"
me.Header.Controls.Add(lt)
Or you could create a Public string on your page, then stick the javascript in this.
Public _JS as string
Page_Load
_JS = "alert('here');" ' Or what ever your javascript is
ASPX Page
<head>
<script type="text/javascript" src="jquery-version.js"></script>
<script type="text/javascript">
$().ready(function(){
<%=(me._JS) %>
});
</script>
</head>
You might consider looking into the ClientScriptManager. This will allow you to inject scripts into the header properly using whatever conditions you require.
Including Custom Client Script in ASP.NET Pages
ClientScriptManager Class
精彩评论