How to avoid multiple $(document).ready() - c#

I work on a ASP.NET application using Jquery. Jquery is really powerfull and I use a lot of it.
In my master page I include all libraries I use and a js file who contain the jquery code available for all the application (interface interactions). In this js File (Main.js) I make some things so I use the $(document).ready( ... etc .. )
But in some pages, who are more complex I need to use some other jquery code.. So I add some head Content with other script tag.. And this the problem, I have to add the $(document).ready() instruction again.
There is a lot of problems with my asp controls with this way to do, the autopostback controls doesn't do their autopostback.. I think this is a problem with the multiple $(document).ready() declaration because when I remove the second one(in the page not in the master page) the controls are working.
So how can I do to add some javascript code in a specific page without multiple $(document).ready() declaration. (I don't want to embed all the jquery code in all pages).
I hope I'm clear enough, thanks for responses
Edit here is code
Master page part
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="SiteMaster" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="Styles/jquery-ui-1.8.9.custom.css" rel="stylesheet" type="text/css" />
<link href="Styles/menu.css" rel="stylesheet" type="text/css" />
<script src="/js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="/js/jquery-ui-1.8.7.custom.min.js" type="text/javascript"></script>
<script src="/js/jquery.cookie.js" type="text/javascript"></script>
<script src="/js/jquery.ui.datepicker-fr.js" type="text/javascript"></script>
<script src="/js/jquery.color.js" type="text/javascript"></script>
<script src="/js/Menu.js" type="text/javascript"></script>
<script src="/js/iphone-style-checkboxes.js" type="text/javascript"></script>
<script src="/js/jquery.tools.min.js" type="text/javascript"></script>
<script src="/js/Main.js" type="text/javascript"></script>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
Some content....
</body>
</html>
Main.js
$(document).ready(function () {
/// <reference path="jquery-1.4.4-vsdoc.js" />
//There is a lot of content here......
});
And A page
<%# Page MasterPageFile="~/Site.master" Language="C#" AutoEventWireup="true" CodeBehind="Dep.aspx.cs" Inherits="Dep" %>
<asp:Content ID="HeadContent1" ContentPlaceHolderID="HeadContent" runat="server">
<link href="../../Styles/nyroModal.css" rel="stylesheet" type="text/css" />
<script src="../../js/jquery.nyroModal.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#tbxDateDebut').datepicker();
$('#tbxDateFin').datepicker();
$('.nyroModal').nyroModal();
});
</script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
//Here comes the controls... (lot of code)
</asp:Content>

main.js
$(document).ready(function () {
//There is a lot of content here......
if ($.pageReady) $.pageReady($);
});
page.js
<script type="text/javascript">
$.pageReady = function() {
// fired on DOM ready
}
</script>

The answer is in your question:
But in some pages, who are more complex I need to use some other jquery code.. So I add some head Content with other script tag.. And this the problem, I have to add the $(document).ready() instruction again.
"But in some pages..."
Unfortunately you have to add a reference for every js file that refers to uncommon elements. That is if you have page 1 with a <div id="element1"> and another page (page 2) with <div id="element676"> you would not want to include all in the Jquery handling into Main.js . In fact that would give an error if you had not yet seen page 2.
Damn you guys are quick.... as I was writing #Raynos gave the correct answer.

well an alternative is to move all of you jquery document ready to the bottom of your page
<body>
... here goes your other html ....
<script>
//$(document).ready(function(){//this is not needed
... here goes the first ready...
//});//this is not needed
//$(document).ready(function(){//this is not needed
... here goes the second ready ... and so on...
//});//this is not needed
</script>
</body>
So in effect you are using document.ready when all other elements are ready :) PS

I'm inclined to think that there's something at work here other than your multiple $(document).ready() calls. AFAIK, multiple calls against $(document).ready() (and even bubbled-up versions, like $('#someid').ready()) shouldn't cause issues as they are all aggregated together silently by jQuery for you.
I'd double-check my syntax for starters, and make sure that all your blocks are properly encapsulated, all statements end with a ;, and all that jazz.

Related

java script error on moving the jquery references to the asp.net master page

I use jquery and I see that currently, Jquery is given a reference in every content page.
I am planning to move all the references to the master page so that it will be easy to update them when its needed.
So , I remove the jquery references from the content page and place them in the head section of the master page as shown below :
<head id="Head1" runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link href="App_Themes/masterStyleSheet.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/redmond/jquery-ui.css"
<asp:ContentPlaceHolder ID="ExtraHeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
When I run the application I get the following error :
JavaScript runtime error: 'jQuery' is undefined
From my research online this is the right way to do it .. but I get the error. Can anyone help me and point out whats wrong or what needs to be done ?
Move the jquery script tag above the jquery ui script tag and remove one of the jquery ui references since you don't need to include them twice:
<head id="Head1" runat="server">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link href="App_Themes/masterStyleSheet.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/redmond/jquery-ui.css"
<asp:ContentPlaceHolder ID="ExtraHeadContent" runat="server">
</asp:ContentPlaceHolder>
</head>
jQuery is undefined since the jquery ui library is trying to use the jQuery reference before it is defined in the jquery-1.9.1.js file.
First, change the order of the call to jQuery UI and jQuery library, all library or plugin that use jQuery need that defined jQuery before you call it, this is for all libraries or framewors:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
then so that you can see in your code you are calling twice a jQuery UI, check this and also if you are calling twice a jQuery or other libraries:
http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js
http://code.jquery.com/ui/1.10.3/jquery-ui.js
you are calling jQuery ui library before jQuery library is loaded
your code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
change it to
call jQuery library file first
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

extending bootstrap select

I want to use the bootstrap framework along with http://silviomoreto.github.io/bootstrap-select/. it just doesnt work. Below are the codes. Please help.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Final_Year_Project_Allocation_System.silviomoreto_bootstrap_select_d4ec9bd.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<link href="bootstrap-select.css" rel="stylesheet" type="text/css" />
<link href="bootstrap-select.css" rel="stylesheet" type="text/css" />
<script src="../bootstrap/js/bootstrap.js" type="text/javascript"></script>
<script src="bootstrap-select.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<select class="selectpicker">
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>
</div>
</form>
</body>
</html>
please help.
I don't see a reference to the actual bootstrap.css ?
You need to have something like (note the order - it's important):
<link href="bootstrap.css" rel="stylesheet" type="text/css" />
<link href="bootstrap-select.css" rel="stylesheet" type="text/css" />
Then the JS
<script src="../bootstrap/js/bootstrap.js" type="text/javascript"></script>
<script src="../bootstrap/js/bootstrap-select.js" type="text/javascript"></script>
Make sure the path is correct of course.
EDIT
I'm also pretty sure that boostrap.js has a dependency on jquery - so make sure you include it as well (before the bootsrap.js).
EDIT 2
I also suspect that your paths are not correct. If this is the path for your javascript:
"../bootstrap/js/bootstrap.js"
Then most probably the path for your css would be (assuming that you just dropped bootstrap as-is and didn't place it in a different folder):
"../bootstrap/css/bootstrap.css"

How to decrease page load time (combine javascript)?

Page created using ASP .NET MVC 2 takes 1.7 sec to load.
It contains 13 js files as shown below. Firebug shows that every js file load returns 304 response but since there are 13 files it may increace page load time a lot.
Chrome audit red alert recomments to combine js files.
How to combine them to single file using ASP.NET MVC 2 automatically or other way to decrease load time ?
There should be separate js files in project to allow to replace them but those should delivered
as single js file probably.
jqgrid, jquery, jquery-ui, tinymce and some jquery plugin js files are used as shown below.
Visual Web Developer Express 2010 is used. Application is running under Mono 2.10/Apache and under Windows/IIS
site.master contains:
<%# Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=0.1" />
<link rel="stylesheet" href="../../themes/redmond/jquery-ui-1.8.12.custom.css" type="text/css" />
<link href="../../Scripts/jqgrid/css/ui.jqgrid.css" rel="stylesheet" />
<link href="../../Content/Css/Site.css" rel="stylesheet" />
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
</title>
<script type="text/javascript">
"use strict";
var BASE_URL = '<%= ResolveUrl("~/") %>';
</script>
<script src="<%= Url.Content("~/Scripts/jquery/jquery-1.7.1.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery-ui-git.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/i18n/jquery.ui.datepicker-et.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.contextmenu-fixed2.js")%>" type="text/javascript"></script>
<% if (CurUser.GetLanguage() == "EST")
{ %>
<script src="<%= Url.Content("~/Scripts/jqgrid/js/i18n/grid.locale-et.js")%>" type="text/javascript"></script>
<% }
else
{ %>
<script src="<%= Url.Content("~/Scripts/jqgrid/js/i18n/grid.locale-en.js")%>" type="text/javascript"></script>
<% } %>
<script type="text/javascript">
$.jgrid.no_legacy_api = true;
$.jgrid.useJSON = true;
</script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqgrid/jquery.jqGrid.src-multiselect1-deleteandsortpatches.js")%>"></script>
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jqgrid/jQuery.jqGrid.dynamicLink.js")%>"></script>
<script src="<%= Url.Content("~/Scripts/json2.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.form.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/TinyMCE/tiny_mce_src.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/TinyMCE/jquery.tinymce.js")%>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/myscripts.js")%>" type="text/javascript"></script>
<script type="text/javascript">
var
$grid;
$(function() {
"use strict";
<% if (TempData["Message"]!=null) {
setTimeout( function() {
showMessage ( '<%= TempData["Message"] as string %>');
...
Update
I tried Oleg suggestion in answer but got error jQuery is not defined as shown in image below. How to fix this ?
IE console does not show any error.
I want suggest you to make one experiment using the Closure Compiler.
First of all you can try to concatenate all the JavaScript and all inline JavaScript code which you use on the page. You should hold the order of files of cause. It seems to me you will have two version of the results: one with CurUser.GetLanguage() === "EST" and another with CurUser.GetLanguage() !== "EST".
After you will have one JavaScript file you can use the Closure Compiler with a compilation_level of ADVANCED_OPTIMIZATIONS (see here) which can remove all unused JavaScript code. As the result you will get subset of jQuery, jQuery UI and other libraries which you really use on the page. The resulting JavaScript code will be other as on another pages, but it could be very small and could be better optimized as any separate files.
I recommend use head.js.
It really helps you to decrease page load time with using separate .js files. You just include one file with something like that:
head.js("/path/to/jquery.js", "/google/analytics.js", "/js/site.js", function() {
// all done
});
http://combres.codeplex.com/ allows you to keep separate javascript files and to combine and minify at runtime.
Works a real treat.
Looks like they've rolled something similar into asp.net 4.5:
http://weblogs.asp.net/scottgu/archive/2011/11/27/new-bundling-and-minification-support-asp-net-4-5-series.aspx
http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
To overcome these type of situation you have many techniques. Some of are :
Page Specific JS : Try to add javascript files according to the requirement. Do not add any unnecessary JS which are not used in page.
GZIP Compression : Apply GZIP compression on pages and static js and css files.
Caching : At the server level (IIS) you caching can be applied on these static files like JS or CSS
http://sixrevisions.com/web-development/decrease-webpage-load-times/
Combine multiple JavaScript files into one JS file
Good Luck !!
Bundling Files Together
Most of the current major browsers limit the number of simultaneous connections per each hostname to six. That means that while six requests are being processed, additional requests for assets on a host will be queued by the browser
Bundling can significantly improve your first page hit download time.
Bundling reduces the number of individual HTTP requests to server by combining multiple CSS files and Javascript files into single CSS file and javascript file.
This site here has a good tutorial on how to add bundling to your application in five easy steps: http://websitespeedoptimizations.com/Bundling.aspx

JQuery don’t work in aspx-page with Masterpage

I have made this example and it works fine on a plain aspx webpage. I use Visual Studio 2010.
Head-part:
<title>Show/hide element</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#CheckBoxShowHide').click(function () {
$("#ShowHideElement").slideToggle();
});
});
</script>
<style type="text/css">
#ShowHideElement
{
width:400px;
height:100px;
background-color:Aqua;
}
</style>
Body-part:
<form id="form1" runat="server">
<asp:CheckBox ID="CheckBoxShowHide" runat="server" Text="Show/hide" />
<div id="ShowHideElement">
This is the element for show/hide
</div>
</form>
When I have a masterpage and the same code on the child webpage JQuery dosent work. The loading of the JQuery javascript file fails. The child page and the masterpage are in the same folder. If I put the code on the masterpage it works fine but I want JQuery on the child page too. Please help me.
I can see another problem as well, you are trying to grab the checkbox ID based on its server ID not ClientID. Once a asp control has been rendered onto the client its ID gets changed. Try the following code:
<title>Show/hide element</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#<%=CheckBoxShowHide.ClientID%>').click(function () {
$("#ShowHideElement").slideToggle();
});
});
</script>
<style type="text/css">
#ShowHideElement
{
width:400px;
height:100px;
background-color:Aqua;
}
</style>
Body-part:
<form id="form1" runat="server">
<asp:CheckBox ID="CheckBoxShowHide" runat="server" Text="Show/hide" />
<div id="ShowHideElement">
This is the element for show/hide
</div>
</form>
The following line is the only thing I changed:
$('#<%=CheckBoxShowHide.ClientID%>').click(function () {
Hope it helps.
Are you sure your page is loading jQuery, use a absolute URL in your master page to reference the jQuery library.
If jQuery is on your masterpage, it will work on your child page.
Master <head>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
</head>
Child <head>
<head>
<script type="text/javascript">
$(document).ready(function () {
//Do Child jQuery Stuff here....
});
</script>
<head>
If you are having issues the only other thing to check is to make sure that your path to the jquery file is right. (ie Maybe it should be ../js/jquery.js)
Use this to make sure that isn't the issue if the other thing I suggested doesn't work:
For your Master Page <head>:
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
Or (if you want to host it)
<head>
<script type="text/javascript" src='<%=ResolveURL("~/js/jquery.js")%>'></script>
</head>
Where ~/ is your root.
You should be able to just place the link to the JQuery library in the HEAD section of the master page. When the page is ran it will generate the HTML content for the master page with the link in the HEAD section, the content page should be able to then make user of the JQuery library. I know we had an issue with how the link was being done. Maybe try linking in the HEAD of the master page like this instead:
<script type="text/javascript" src='<% = ResolveURL("~/js/jquery.js") %>' ></script>
The '<% %>' is a way to do inline server side code as the page loads, so the page will inject the correct src given the location of the URL.

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

I am stuck with this error and found a work around and the solutions works for me, but i i would like to know is it the best way to fix the issue and i want to make sure that it wont affect any other pages badly. Hope the experts will help.
If this was the best solution then many of you can save your heads.
This error occurs when a code block is placed in the MasterPage. Place the code block in a placeholder to resolve the issue.When adding AJAX extenders to your Web page, it will attempt to register scripts in the head. If code blocks are present in the MasterPage, an error might occur.
To resolve this issue, simply move the code block into a placeholder in the head of your MasterPage, like so:
<head id="Head1" runat="server">
<title>Untitled Page</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="myPlaceholder" runat="server">
<script language="javascript" type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/global.js")%>"></script>
</asp:ContentPlaceHolder>
<asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>
The error is logical you can not confuse the rendered controls after they rendered by using the <%= %>
One way to solve this issue is to use a literal control, and render the script line on code behind.
<asp:ContentPlaceHolder ID="myPlaceholder" runat="server">
<asp:Literal runat="server" ID="txtIncludeScript" EnableViewState="false"></asp:Literal>
</asp:ContentPlaceHolder>
and on code behind. Check for null because if you change the placeholder the literal is null. Also set EnableViewState=false because you set it on every Page_Load and you do not wish to save it to viewstate.
if(txtIncludeScript != null)
{
txtIncludeScript.Text =
string.Format("<script language=\"javascript\" type=\"text/javascript\" src=\"{0}\"></script>",
Page.ResolveClientUrl("~/javascript/global.js"));
}
ContentPlaceHolder requires a master page, so you can replace that tag with some other element that can be ran at the server in case your page does not have a master page and you cannot get rid of the
<head id="Head1" runat="server">
<title>Untitled Page</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
<div runat="server">
<script language="javascript" type="text/javascript" src="<%= Page.ResolveClientURL("~/javascript/global.js")%>"></script>
</div>
<asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>

Categories

Resources