ASP.NET Webforms, JavaScript in user controls
up vote
6
down vote
favorite
We are struggling a little regarding the right implementation of JavaScript in our solution (APS.NET Webforms).
We want to have all (or at least as much as possible) of our javascript at the bottom of pages, according to best practice, so pages load HTML and CSS first and give a better user experience.
There is a lot of jQuery code throughout our project that is often specific to certain controls, so we don't want that to load on every page.
Currently jQuery itself, including jQuery UI are positioned at the top of pages, so that we can have jQuery usages in controls (either from js files or sometimes inline code), however, we want to move all that stuff down to the bottom of the page. We have already added a contentplaceholder ("JavascriptFooter") at the bottom of the page, so we can place javascript from pages in the footer of the page, but we're stuck on the controls.
What are best practices for this? Should we externalize all JS and in the JS check if a control is loaded? But then we will be showing too much stuff all the time. Or is there another way?
asp.net webforms
|
show 1 more comment
up vote
6
down vote
favorite
We are struggling a little regarding the right implementation of JavaScript in our solution (APS.NET Webforms).
We want to have all (or at least as much as possible) of our javascript at the bottom of pages, according to best practice, so pages load HTML and CSS first and give a better user experience.
There is a lot of jQuery code throughout our project that is often specific to certain controls, so we don't want that to load on every page.
Currently jQuery itself, including jQuery UI are positioned at the top of pages, so that we can have jQuery usages in controls (either from js files or sometimes inline code), however, we want to move all that stuff down to the bottom of the page. We have already added a contentplaceholder ("JavascriptFooter") at the bottom of the page, so we can place javascript from pages in the footer of the page, but we're stuck on the controls.
What are best practices for this? Should we externalize all JS and in the JS check if a control is loaded? But then we will be showing too much stuff all the time. Or is there another way?
asp.net webforms
1
Why not defer the execution of the scripts until the DOM is ready? i.e. ($(function(){ ..On Ready Code Goes Here .. });
– ctorx
Sep 6 '12 at 15:33
($(function(){ console.log("Works?"); }));
in the head throws the error$ is not defined
, with jQuery initialized at the bottom.
– Richard
Sep 7 '12 at 8:57
You would need to include Jquery before you executed that script...and you could easily pull it in from a CDN like Google. I typically include Jquery in the head, from a CDN and everything else at the bottom.
– ctorx
Sep 7 '12 at 15:27
Well that's the whole point of the tread. How do I put JS from controls in the footer, rather that putting jQuery at the top of the page.
– Richard
Sep 8 '12 at 16:31
How do you want to add the JavaScript? Do you intend to do this within the markup of the control or the control code behind?
– ctorx
Sep 8 '12 at 20:08
|
show 1 more comment
up vote
6
down vote
favorite
up vote
6
down vote
favorite
We are struggling a little regarding the right implementation of JavaScript in our solution (APS.NET Webforms).
We want to have all (or at least as much as possible) of our javascript at the bottom of pages, according to best practice, so pages load HTML and CSS first and give a better user experience.
There is a lot of jQuery code throughout our project that is often specific to certain controls, so we don't want that to load on every page.
Currently jQuery itself, including jQuery UI are positioned at the top of pages, so that we can have jQuery usages in controls (either from js files or sometimes inline code), however, we want to move all that stuff down to the bottom of the page. We have already added a contentplaceholder ("JavascriptFooter") at the bottom of the page, so we can place javascript from pages in the footer of the page, but we're stuck on the controls.
What are best practices for this? Should we externalize all JS and in the JS check if a control is loaded? But then we will be showing too much stuff all the time. Or is there another way?
asp.net webforms
We are struggling a little regarding the right implementation of JavaScript in our solution (APS.NET Webforms).
We want to have all (or at least as much as possible) of our javascript at the bottom of pages, according to best practice, so pages load HTML and CSS first and give a better user experience.
There is a lot of jQuery code throughout our project that is often specific to certain controls, so we don't want that to load on every page.
Currently jQuery itself, including jQuery UI are positioned at the top of pages, so that we can have jQuery usages in controls (either from js files or sometimes inline code), however, we want to move all that stuff down to the bottom of the page. We have already added a contentplaceholder ("JavascriptFooter") at the bottom of the page, so we can place javascript from pages in the footer of the page, but we're stuck on the controls.
What are best practices for this? Should we externalize all JS and in the JS check if a control is loaded? But then we will be showing too much stuff all the time. Or is there another way?
asp.net webforms
asp.net webforms
asked Sep 6 '12 at 15:12
Richard
3,12352445
3,12352445
1
Why not defer the execution of the scripts until the DOM is ready? i.e. ($(function(){ ..On Ready Code Goes Here .. });
– ctorx
Sep 6 '12 at 15:33
($(function(){ console.log("Works?"); }));
in the head throws the error$ is not defined
, with jQuery initialized at the bottom.
– Richard
Sep 7 '12 at 8:57
You would need to include Jquery before you executed that script...and you could easily pull it in from a CDN like Google. I typically include Jquery in the head, from a CDN and everything else at the bottom.
– ctorx
Sep 7 '12 at 15:27
Well that's the whole point of the tread. How do I put JS from controls in the footer, rather that putting jQuery at the top of the page.
– Richard
Sep 8 '12 at 16:31
How do you want to add the JavaScript? Do you intend to do this within the markup of the control or the control code behind?
– ctorx
Sep 8 '12 at 20:08
|
show 1 more comment
1
Why not defer the execution of the scripts until the DOM is ready? i.e. ($(function(){ ..On Ready Code Goes Here .. });
– ctorx
Sep 6 '12 at 15:33
($(function(){ console.log("Works?"); }));
in the head throws the error$ is not defined
, with jQuery initialized at the bottom.
– Richard
Sep 7 '12 at 8:57
You would need to include Jquery before you executed that script...and you could easily pull it in from a CDN like Google. I typically include Jquery in the head, from a CDN and everything else at the bottom.
– ctorx
Sep 7 '12 at 15:27
Well that's the whole point of the tread. How do I put JS from controls in the footer, rather that putting jQuery at the top of the page.
– Richard
Sep 8 '12 at 16:31
How do you want to add the JavaScript? Do you intend to do this within the markup of the control or the control code behind?
– ctorx
Sep 8 '12 at 20:08
1
1
Why not defer the execution of the scripts until the DOM is ready? i.e. ($(function(){ ..On Ready Code Goes Here .. });
– ctorx
Sep 6 '12 at 15:33
Why not defer the execution of the scripts until the DOM is ready? i.e. ($(function(){ ..On Ready Code Goes Here .. });
– ctorx
Sep 6 '12 at 15:33
($(function(){ console.log("Works?"); }));
in the head throws the error $ is not defined
, with jQuery initialized at the bottom.– Richard
Sep 7 '12 at 8:57
($(function(){ console.log("Works?"); }));
in the head throws the error $ is not defined
, with jQuery initialized at the bottom.– Richard
Sep 7 '12 at 8:57
You would need to include Jquery before you executed that script...and you could easily pull it in from a CDN like Google. I typically include Jquery in the head, from a CDN and everything else at the bottom.
– ctorx
Sep 7 '12 at 15:27
You would need to include Jquery before you executed that script...and you could easily pull it in from a CDN like Google. I typically include Jquery in the head, from a CDN and everything else at the bottom.
– ctorx
Sep 7 '12 at 15:27
Well that's the whole point of the tread. How do I put JS from controls in the footer, rather that putting jQuery at the top of the page.
– Richard
Sep 8 '12 at 16:31
Well that's the whole point of the tread. How do I put JS from controls in the footer, rather that putting jQuery at the top of the page.
– Richard
Sep 8 '12 at 16:31
How do you want to add the JavaScript? Do you intend to do this within the markup of the control or the control code behind?
– ctorx
Sep 8 '12 at 20:08
How do you want to add the JavaScript? Do you intend to do this within the markup of the control or the control code behind?
– ctorx
Sep 8 '12 at 20:08
|
show 1 more comment
3 Answers
3
active
oldest
votes
up vote
4
down vote
accepted
First, I would suggest loading Jquery from a CDN. Here is the code for Google:
<script type="text/javascript">
document.write(["<script type='text/javascript' src='",
("https:" == document.location.protocol) ? "https://" : "http://",
"ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>"].join(''));
</script>
That way, if the visitor has been served this on another site, it will already be cached. In addition, it will download in parallel as it is being delivered from a different host.
I also agree with @ctorx - you should use document ready execution.
In addition, you could use a ScriptManager
and create all your control specific JS in the code behind of each control (probably a good idea anyways if that control is the only object utilizing that JS) - all this code renders at the bottom of the page.
Example:
Page pg = (Page)System.Web.HttpContext.Current.Handler; // or this.Page in .ascx
ScriptManager.RegisterStartupScript(pg, typeof(Page), "myJS", "[... your code ]", true);
Thanks, we do use CDN's for jQuery(-UI), but still, we would want to load them at the bottom.
– Richard
Sep 7 '12 at 8:45
2
Protocol can be resolved automatically, just type script url as"//ajax.googleapis.com/..."
– Pavel Hodek
Dec 20 '12 at 11:46
add a comment |
up vote
1
down vote
I bet there are as many solutions to this as there are companies using webforms. That said, you can always use the request context to store the necessary scripts and then write them before the page renders.
You could possibly use requireJS as well. I'm no expert, but there are alot of options and it would handle script loading timeouts, circular dependencies, defining multiple dependencies, etc.
add a comment |
up vote
1
down vote
Firstly, the best approach is to externalize the JavaScript from controls in a JS file that is loaded on the first request to your site and all subsequent requests (i.e. site.js). This file will then be cached by the browser and users won't have to download the JS over and over again as they would if the JS stays in the controls.
Next, you need to create a mechanism to only execute the portions of script that are relevant to the executing page or control.
There are several ways you can achieve this, however if I was in your situation I would do it this way.
Identify a page level element that wraps most of your content ... typically people call this wrapper
. Dynamically add a custom attribute to wrapper called "data-js
". Set the value of "data-js" dynamically (on the server side) from either a page or a user/custom control. Allow it to have multiple keys delimited by a pipe (|) or other character.
<div class="wrapper" data-js="funtion1|function2">
<!-- Page content goes here -->
</div>
Leverage jQuery to look for this attribute on DOM ready, and execute custom JS functions based on the value in data-js attribute. That function will contain only code that is relevant for the current page or controls.
$(function(){
var funcKeys = $('.wrapper').attr('data-js');
if(funcKeys != null)
{
var funcs = funcKeys.split('|');
for(var i=0; i< funcs.length; i++) {
var funcName = eval(funcs[i]);
if(typeof funcName == 'function') {
funcName();
}
}
}
});
Using this approach you only need the jQuery CDN reference, a reference to your site's JS file and the above snippet of code in your layout.
Then you need simply include the page/control specific functions in your site specific JS file, like so:
function function1() {
alert("This is function 1");
}
function function2() {
alert("This is function 2");
}
I hope this helps.
FYI, I also setup a fiddle for you to play with how it works:
http://jsfiddle.net/hh84f/1/
Thanks, interesting solution, I'll have a look at it. Alternatively the same technique could be used to load specific JS files rather than executing functions.
– Richard
Sep 9 '12 at 14:51
Indeed. I was going for one cacheable http hit on first request, but separate files could be a cleaner solution from a maintenance standpoint if the site has a lot of JS.
– ctorx
Sep 9 '12 at 15:03
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f12303162%2fasp-net-webforms-javascript-in-user-controls%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
4
down vote
accepted
First, I would suggest loading Jquery from a CDN. Here is the code for Google:
<script type="text/javascript">
document.write(["<script type='text/javascript' src='",
("https:" == document.location.protocol) ? "https://" : "http://",
"ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>"].join(''));
</script>
That way, if the visitor has been served this on another site, it will already be cached. In addition, it will download in parallel as it is being delivered from a different host.
I also agree with @ctorx - you should use document ready execution.
In addition, you could use a ScriptManager
and create all your control specific JS in the code behind of each control (probably a good idea anyways if that control is the only object utilizing that JS) - all this code renders at the bottom of the page.
Example:
Page pg = (Page)System.Web.HttpContext.Current.Handler; // or this.Page in .ascx
ScriptManager.RegisterStartupScript(pg, typeof(Page), "myJS", "[... your code ]", true);
Thanks, we do use CDN's for jQuery(-UI), but still, we would want to load them at the bottom.
– Richard
Sep 7 '12 at 8:45
2
Protocol can be resolved automatically, just type script url as"//ajax.googleapis.com/..."
– Pavel Hodek
Dec 20 '12 at 11:46
add a comment |
up vote
4
down vote
accepted
First, I would suggest loading Jquery from a CDN. Here is the code for Google:
<script type="text/javascript">
document.write(["<script type='text/javascript' src='",
("https:" == document.location.protocol) ? "https://" : "http://",
"ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>"].join(''));
</script>
That way, if the visitor has been served this on another site, it will already be cached. In addition, it will download in parallel as it is being delivered from a different host.
I also agree with @ctorx - you should use document ready execution.
In addition, you could use a ScriptManager
and create all your control specific JS in the code behind of each control (probably a good idea anyways if that control is the only object utilizing that JS) - all this code renders at the bottom of the page.
Example:
Page pg = (Page)System.Web.HttpContext.Current.Handler; // or this.Page in .ascx
ScriptManager.RegisterStartupScript(pg, typeof(Page), "myJS", "[... your code ]", true);
Thanks, we do use CDN's for jQuery(-UI), but still, we would want to load them at the bottom.
– Richard
Sep 7 '12 at 8:45
2
Protocol can be resolved automatically, just type script url as"//ajax.googleapis.com/..."
– Pavel Hodek
Dec 20 '12 at 11:46
add a comment |
up vote
4
down vote
accepted
up vote
4
down vote
accepted
First, I would suggest loading Jquery from a CDN. Here is the code for Google:
<script type="text/javascript">
document.write(["<script type='text/javascript' src='",
("https:" == document.location.protocol) ? "https://" : "http://",
"ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>"].join(''));
</script>
That way, if the visitor has been served this on another site, it will already be cached. In addition, it will download in parallel as it is being delivered from a different host.
I also agree with @ctorx - you should use document ready execution.
In addition, you could use a ScriptManager
and create all your control specific JS in the code behind of each control (probably a good idea anyways if that control is the only object utilizing that JS) - all this code renders at the bottom of the page.
Example:
Page pg = (Page)System.Web.HttpContext.Current.Handler; // or this.Page in .ascx
ScriptManager.RegisterStartupScript(pg, typeof(Page), "myJS", "[... your code ]", true);
First, I would suggest loading Jquery from a CDN. Here is the code for Google:
<script type="text/javascript">
document.write(["<script type='text/javascript' src='",
("https:" == document.location.protocol) ? "https://" : "http://",
"ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>"].join(''));
</script>
That way, if the visitor has been served this on another site, it will already be cached. In addition, it will download in parallel as it is being delivered from a different host.
I also agree with @ctorx - you should use document ready execution.
In addition, you could use a ScriptManager
and create all your control specific JS in the code behind of each control (probably a good idea anyways if that control is the only object utilizing that JS) - all this code renders at the bottom of the page.
Example:
Page pg = (Page)System.Web.HttpContext.Current.Handler; // or this.Page in .ascx
ScriptManager.RegisterStartupScript(pg, typeof(Page), "myJS", "[... your code ]", true);
answered Sep 6 '12 at 17:04
CoderMarkus
9181723
9181723
Thanks, we do use CDN's for jQuery(-UI), but still, we would want to load them at the bottom.
– Richard
Sep 7 '12 at 8:45
2
Protocol can be resolved automatically, just type script url as"//ajax.googleapis.com/..."
– Pavel Hodek
Dec 20 '12 at 11:46
add a comment |
Thanks, we do use CDN's for jQuery(-UI), but still, we would want to load them at the bottom.
– Richard
Sep 7 '12 at 8:45
2
Protocol can be resolved automatically, just type script url as"//ajax.googleapis.com/..."
– Pavel Hodek
Dec 20 '12 at 11:46
Thanks, we do use CDN's for jQuery(-UI), but still, we would want to load them at the bottom.
– Richard
Sep 7 '12 at 8:45
Thanks, we do use CDN's for jQuery(-UI), but still, we would want to load them at the bottom.
– Richard
Sep 7 '12 at 8:45
2
2
Protocol can be resolved automatically, just type script url as
"//ajax.googleapis.com/..."
– Pavel Hodek
Dec 20 '12 at 11:46
Protocol can be resolved automatically, just type script url as
"//ajax.googleapis.com/..."
– Pavel Hodek
Dec 20 '12 at 11:46
add a comment |
up vote
1
down vote
I bet there are as many solutions to this as there are companies using webforms. That said, you can always use the request context to store the necessary scripts and then write them before the page renders.
You could possibly use requireJS as well. I'm no expert, but there are alot of options and it would handle script loading timeouts, circular dependencies, defining multiple dependencies, etc.
add a comment |
up vote
1
down vote
I bet there are as many solutions to this as there are companies using webforms. That said, you can always use the request context to store the necessary scripts and then write them before the page renders.
You could possibly use requireJS as well. I'm no expert, but there are alot of options and it would handle script loading timeouts, circular dependencies, defining multiple dependencies, etc.
add a comment |
up vote
1
down vote
up vote
1
down vote
I bet there are as many solutions to this as there are companies using webforms. That said, you can always use the request context to store the necessary scripts and then write them before the page renders.
You could possibly use requireJS as well. I'm no expert, but there are alot of options and it would handle script loading timeouts, circular dependencies, defining multiple dependencies, etc.
I bet there are as many solutions to this as there are companies using webforms. That said, you can always use the request context to store the necessary scripts and then write them before the page renders.
You could possibly use requireJS as well. I'm no expert, but there are alot of options and it would handle script loading timeouts, circular dependencies, defining multiple dependencies, etc.
answered Sep 6 '12 at 15:27
Rob Allen
2,13112444
2,13112444
add a comment |
add a comment |
up vote
1
down vote
Firstly, the best approach is to externalize the JavaScript from controls in a JS file that is loaded on the first request to your site and all subsequent requests (i.e. site.js). This file will then be cached by the browser and users won't have to download the JS over and over again as they would if the JS stays in the controls.
Next, you need to create a mechanism to only execute the portions of script that are relevant to the executing page or control.
There are several ways you can achieve this, however if I was in your situation I would do it this way.
Identify a page level element that wraps most of your content ... typically people call this wrapper
. Dynamically add a custom attribute to wrapper called "data-js
". Set the value of "data-js" dynamically (on the server side) from either a page or a user/custom control. Allow it to have multiple keys delimited by a pipe (|) or other character.
<div class="wrapper" data-js="funtion1|function2">
<!-- Page content goes here -->
</div>
Leverage jQuery to look for this attribute on DOM ready, and execute custom JS functions based on the value in data-js attribute. That function will contain only code that is relevant for the current page or controls.
$(function(){
var funcKeys = $('.wrapper').attr('data-js');
if(funcKeys != null)
{
var funcs = funcKeys.split('|');
for(var i=0; i< funcs.length; i++) {
var funcName = eval(funcs[i]);
if(typeof funcName == 'function') {
funcName();
}
}
}
});
Using this approach you only need the jQuery CDN reference, a reference to your site's JS file and the above snippet of code in your layout.
Then you need simply include the page/control specific functions in your site specific JS file, like so:
function function1() {
alert("This is function 1");
}
function function2() {
alert("This is function 2");
}
I hope this helps.
FYI, I also setup a fiddle for you to play with how it works:
http://jsfiddle.net/hh84f/1/
Thanks, interesting solution, I'll have a look at it. Alternatively the same technique could be used to load specific JS files rather than executing functions.
– Richard
Sep 9 '12 at 14:51
Indeed. I was going for one cacheable http hit on first request, but separate files could be a cleaner solution from a maintenance standpoint if the site has a lot of JS.
– ctorx
Sep 9 '12 at 15:03
add a comment |
up vote
1
down vote
Firstly, the best approach is to externalize the JavaScript from controls in a JS file that is loaded on the first request to your site and all subsequent requests (i.e. site.js). This file will then be cached by the browser and users won't have to download the JS over and over again as they would if the JS stays in the controls.
Next, you need to create a mechanism to only execute the portions of script that are relevant to the executing page or control.
There are several ways you can achieve this, however if I was in your situation I would do it this way.
Identify a page level element that wraps most of your content ... typically people call this wrapper
. Dynamically add a custom attribute to wrapper called "data-js
". Set the value of "data-js" dynamically (on the server side) from either a page or a user/custom control. Allow it to have multiple keys delimited by a pipe (|) or other character.
<div class="wrapper" data-js="funtion1|function2">
<!-- Page content goes here -->
</div>
Leverage jQuery to look for this attribute on DOM ready, and execute custom JS functions based on the value in data-js attribute. That function will contain only code that is relevant for the current page or controls.
$(function(){
var funcKeys = $('.wrapper').attr('data-js');
if(funcKeys != null)
{
var funcs = funcKeys.split('|');
for(var i=0; i< funcs.length; i++) {
var funcName = eval(funcs[i]);
if(typeof funcName == 'function') {
funcName();
}
}
}
});
Using this approach you only need the jQuery CDN reference, a reference to your site's JS file and the above snippet of code in your layout.
Then you need simply include the page/control specific functions in your site specific JS file, like so:
function function1() {
alert("This is function 1");
}
function function2() {
alert("This is function 2");
}
I hope this helps.
FYI, I also setup a fiddle for you to play with how it works:
http://jsfiddle.net/hh84f/1/
Thanks, interesting solution, I'll have a look at it. Alternatively the same technique could be used to load specific JS files rather than executing functions.
– Richard
Sep 9 '12 at 14:51
Indeed. I was going for one cacheable http hit on first request, but separate files could be a cleaner solution from a maintenance standpoint if the site has a lot of JS.
– ctorx
Sep 9 '12 at 15:03
add a comment |
up vote
1
down vote
up vote
1
down vote
Firstly, the best approach is to externalize the JavaScript from controls in a JS file that is loaded on the first request to your site and all subsequent requests (i.e. site.js). This file will then be cached by the browser and users won't have to download the JS over and over again as they would if the JS stays in the controls.
Next, you need to create a mechanism to only execute the portions of script that are relevant to the executing page or control.
There are several ways you can achieve this, however if I was in your situation I would do it this way.
Identify a page level element that wraps most of your content ... typically people call this wrapper
. Dynamically add a custom attribute to wrapper called "data-js
". Set the value of "data-js" dynamically (on the server side) from either a page or a user/custom control. Allow it to have multiple keys delimited by a pipe (|) or other character.
<div class="wrapper" data-js="funtion1|function2">
<!-- Page content goes here -->
</div>
Leverage jQuery to look for this attribute on DOM ready, and execute custom JS functions based on the value in data-js attribute. That function will contain only code that is relevant for the current page or controls.
$(function(){
var funcKeys = $('.wrapper').attr('data-js');
if(funcKeys != null)
{
var funcs = funcKeys.split('|');
for(var i=0; i< funcs.length; i++) {
var funcName = eval(funcs[i]);
if(typeof funcName == 'function') {
funcName();
}
}
}
});
Using this approach you only need the jQuery CDN reference, a reference to your site's JS file and the above snippet of code in your layout.
Then you need simply include the page/control specific functions in your site specific JS file, like so:
function function1() {
alert("This is function 1");
}
function function2() {
alert("This is function 2");
}
I hope this helps.
FYI, I also setup a fiddle for you to play with how it works:
http://jsfiddle.net/hh84f/1/
Firstly, the best approach is to externalize the JavaScript from controls in a JS file that is loaded on the first request to your site and all subsequent requests (i.e. site.js). This file will then be cached by the browser and users won't have to download the JS over and over again as they would if the JS stays in the controls.
Next, you need to create a mechanism to only execute the portions of script that are relevant to the executing page or control.
There are several ways you can achieve this, however if I was in your situation I would do it this way.
Identify a page level element that wraps most of your content ... typically people call this wrapper
. Dynamically add a custom attribute to wrapper called "data-js
". Set the value of "data-js" dynamically (on the server side) from either a page or a user/custom control. Allow it to have multiple keys delimited by a pipe (|) or other character.
<div class="wrapper" data-js="funtion1|function2">
<!-- Page content goes here -->
</div>
Leverage jQuery to look for this attribute on DOM ready, and execute custom JS functions based on the value in data-js attribute. That function will contain only code that is relevant for the current page or controls.
$(function(){
var funcKeys = $('.wrapper').attr('data-js');
if(funcKeys != null)
{
var funcs = funcKeys.split('|');
for(var i=0; i< funcs.length; i++) {
var funcName = eval(funcs[i]);
if(typeof funcName == 'function') {
funcName();
}
}
}
});
Using this approach you only need the jQuery CDN reference, a reference to your site's JS file and the above snippet of code in your layout.
Then you need simply include the page/control specific functions in your site specific JS file, like so:
function function1() {
alert("This is function 1");
}
function function2() {
alert("This is function 2");
}
I hope this helps.
FYI, I also setup a fiddle for you to play with how it works:
http://jsfiddle.net/hh84f/1/
edited Sep 9 '12 at 3:54
answered Sep 8 '12 at 20:39
ctorx
4,36543050
4,36543050
Thanks, interesting solution, I'll have a look at it. Alternatively the same technique could be used to load specific JS files rather than executing functions.
– Richard
Sep 9 '12 at 14:51
Indeed. I was going for one cacheable http hit on first request, but separate files could be a cleaner solution from a maintenance standpoint if the site has a lot of JS.
– ctorx
Sep 9 '12 at 15:03
add a comment |
Thanks, interesting solution, I'll have a look at it. Alternatively the same technique could be used to load specific JS files rather than executing functions.
– Richard
Sep 9 '12 at 14:51
Indeed. I was going for one cacheable http hit on first request, but separate files could be a cleaner solution from a maintenance standpoint if the site has a lot of JS.
– ctorx
Sep 9 '12 at 15:03
Thanks, interesting solution, I'll have a look at it. Alternatively the same technique could be used to load specific JS files rather than executing functions.
– Richard
Sep 9 '12 at 14:51
Thanks, interesting solution, I'll have a look at it. Alternatively the same technique could be used to load specific JS files rather than executing functions.
– Richard
Sep 9 '12 at 14:51
Indeed. I was going for one cacheable http hit on first request, but separate files could be a cleaner solution from a maintenance standpoint if the site has a lot of JS.
– ctorx
Sep 9 '12 at 15:03
Indeed. I was going for one cacheable http hit on first request, but separate files could be a cleaner solution from a maintenance standpoint if the site has a lot of JS.
– ctorx
Sep 9 '12 at 15:03
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f12303162%2fasp-net-webforms-javascript-in-user-controls%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Why not defer the execution of the scripts until the DOM is ready? i.e. ($(function(){ ..On Ready Code Goes Here .. });
– ctorx
Sep 6 '12 at 15:33
($(function(){ console.log("Works?"); }));
in the head throws the error$ is not defined
, with jQuery initialized at the bottom.– Richard
Sep 7 '12 at 8:57
You would need to include Jquery before you executed that script...and you could easily pull it in from a CDN like Google. I typically include Jquery in the head, from a CDN and everything else at the bottom.
– ctorx
Sep 7 '12 at 15:27
Well that's the whole point of the tread. How do I put JS from controls in the footer, rather that putting jQuery at the top of the page.
– Richard
Sep 8 '12 at 16:31
How do you want to add the JavaScript? Do you intend to do this within the markup of the control or the control code behind?
– ctorx
Sep 8 '12 at 20:08