How to run jquery script if html page is the home page…?

谁说我不能喝 提交于 2019-12-03 06:02:29

I'm posting another answer in case you can't implement the Master Page solution.

You could use a flag element to tell jQuery it's the homepage, because the URL solutions posted earlier can easily break.

Somewhere in your Homepage content, simply place this.

<span id="homepage-flag" style="display: none" />

And then using jQuery, check if the element exists and run your code. It's a pretty poor solution but it will work if you can't get my other answer to work.

if($("#homepage-flag").length > 0) {
    // run code for homepage
}

How about a script Content Place holder that's inside the <head> of the MasterPage, and then placing content inside the placeholder from your homepage.

Basically..

In your Master Page

<head>
<title>hello</title> etc...
// add jQuery here

<asp:ContentPlaceHolder ID="jQueryCode" runat="server"></asp:ContentPlaceHolder>

And then in your Home Page

<asp:Content ContentPlaceHolderId="jQueryCode" runat="server">
    // run jQuery script here
</asp:Content>

Also - if you're not using jQuery on the other pages, you can remove it from the MasterPage and add it right above your script inside the home page <asp:Content />

You shouldn't, but you could probably do something like this:

if(window.location.pathname == "{home page}")
{
  //run home page jquery.
}

BUT... my advise would be to create a content section on the home page that gets placed into the HEAD and put the jQuery into there instead of the masterpage. No reason to include it in the masterpage if it's not used everywhere...

if you're using vb.net, you can use the content placeholder as mentioned above but just use a little codebehind on the masterpage vb file to hide/show the placeholder:

 If Request.Url.AbsolutePath.ToLower = "/index.aspx" Then
    jQueryCode.Visible = true
End If

(make sure to set the default view to visible:false first before rebuilding like this:)

<asp:Content ContentPlaceHolderId="jQueryCode" runat="server" visible="false"> 
    // run jQuery script here 
</asp:Content> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!