Run javascript code that is specific to the view - javascript

In my ASP.NET MVC4 application I got 1 javascript file for my functions across the site.
This works pretty good - however I want to run certain code in certain views.
Usually I would solve this by simply putting a short script tag in the view calling the desired function.
However I load my js files at the bottom of the body tag so this script tag would call a function before it being loaded which would obviously not work.
How can I call individual parts of my js file from different views while keeping my js files at the bottom of the body?

There are a few things going on here.
I would not be putting JavaScript directly in the page. Many reasons for this, and is not the focus of your question, but something I wanted to bring up.
You can have a separate JS file that gets loaded after your main JS file that actually does the call to the functions from "main".

My approach is to tag said views with an id:
<div id="specific-page-name"></div>
Then in my javascript simply do:
if ($('#specific-page-name').length) {
// Run code
}
This way you can still separate your views from js code.
Finally, if I have to use model data in js I can do something like:
<div data-model-data="#Model.Data"></div>
And simply read it as:
$('div').data('model-data');

I'm detailing the answer given by Matt in his comment : in your layout, you can specify that you want some additional HTML content (in your case, that will be your JS). You'll want to add it after your main JS block.
#RenderSection("AddScripts", required: false)
Then in your view, you can add a section and it won't be rendered in the view, but in the corresponding section in the layout (after your main JS block).
#section AddScripts {
<script type="text/javascript">
...
</script>
}

Related

How to have javascript work on php loaded content?

I have a php file that loads a different form based on a identifier passed in with a GET request.
Everything works.... except my Javascript/jQuery. Is there a way to re-load my javascript to get it to work on the form?
Or will I need to something else entirely ? like a template system?
Currently, when the page is being loaded by the browser it is commenting out my Javascript script tag that loads my functions.js file. I'm assuming this is because it is because the code relies on a form and as the form hadn't been loaded yet, some kind of error forces the script to be commented out.
You can rectify your problem in two ways:-
1. Put you complete javascript/jQuery code at the bottom of the page (very last) inside (<script></script>)
Or
2. Wrap your complete code inside $(document).ready(function(){ ...//your code ....});
Note:-
a. If you are trying to include an external javascript/jQuery file which have the custom code,then also include it at the bottom of the current page.
b. Take care that proper jquery library (if needed) will added before your code

MVC3 Move Validation Blocks

I'm attempting to place all JavaScript at the bottom of a page. If I move jquery to the bottom it breaks validation on the page. Is there a way to move validation to the bottom of the page.
No, jQuery must be at the top of the page, but most everything else can come after it.
The best practice is to put all of your styles at the top of the page and all of your scripts at the bottom of the page. You will need to put the references to your JavaScript files above your page specific JavaScript.
Its easy to do in MVC3 if you use helper methods.
The process goes like this:
Create helper methods for storing the scripts in the ViewContext
Add scripts and references to JavaScript files in the ViewContext in any of your views and partial views
Render the scripts at the bottom of the page in the order you need them
If this seems like a lot, take a look at this post:
MVC executing view code before layout code and ruining my script order
The helper methods simplify what would otherwise be very messy code. Good luck!

Debug a script that sits in a partial view

Why I can't debug scripts that reside in a partial view, that gets created in runtime?
To see the script in the list of scripts (in Chrome for example) and debug it, I have to move it to the "regular" view on the upper level or I have to move it to a separate .js file.
But what, if the script so small that I don't want to move it anywhere, and still want to be able to debug it?
If you do not load the partial view via ajax (the view is in place at the initial page rendering) you can use 'debugger'. If the code you want to run is added to the dom IE will not know where the actual code is located that you want to debug. So:
// javascript
var foo = 2;
debugger;
// more javascript
There's a much better way to do this now, just use the syntax
//## sourceURL=someValue
immediately after opening your script tag. Example:
<script type="text/javascript">
//## sourceURL=_fooPartialView.cshtml
function foo() {}
</script>
--edit--
Apparently due to some IE compatibility issue javascript source mapping has been changed from the above to:
//# sourceURL=_fooPartialView.cshtml
Also note, although not mentioned earlier, the ## was only necessary for source mapping in razor views since "#" had other significance.
It's generally considered poor practice to include a script inside of a partial view. You could run into all kinds of issues with multiple script references and performance. The better approach here is to ensure the script gets moved up to a placeholder in your head tag. For a few examples on this, check out:
Linking JavaScript Libraries in User Controls
and
Include JavaScript file in partial views
If you insist on loading the script from the partial, the 'debugger' approach above is very effective.

Dynamically adding and removing javascript/css with Jquery (or other library)

I am trying to compare having a 1 page app with clientside routing to having a asp mvc app which just routes to html files, to see which is more appropriate for my current project. As I have no need for any Asp Mvc features its all javascript/html which communicates with a web service.
However one problem I can forsee with the one page app is that my site isnt really 1 page, so I would be having to have on main index.html which contained all shared resources. Then dynamically load in new pages based on the hashbang and add in any required scripts and css. This doesn't seem to hard as Jquery I believe provides a .load() method or something similar to get external resources... my problem though is getting rid of them once I am done...
Is there any way to do this, so you target ONLY certain script/link tags, can you give them Ids or something?
Any help on this would be great...
== EDIT ==
Added a simple example to show what I mean:
<!-- Script already in page -->
<script type="text/javascript" src="scripts/script1.js"></script>
<!-- Dynamically added script -->
<script type="text/javascript">
// some javascript
</script>
How can you tell which ones you should remove? If you could apply an id or uniqueness to each script then it may be ok, but thats what i am getting at with this question.
There are zero benefits to "removing resources." When a script has been loaded, removing the script tag from the page later has no purpose--it won't improve your browser performance at all, nor will it harm it to keep the files around.
Simply add your resources as needed and write your code such that it won't execute erroneously.
I'm not shre i understand why you would like to do that but link element (for css) and script (for js) are elements like any other and they can be deleted with remove().

How Jammit handle view specific JavaScript

I'm trying to adopt Jammit in my Rails application.
Default config provided in documentation grabs all js files including view specific javascript:
embed_assets: on
javascripts:
workspace:
- public/javascripts/vendor/jquery.js
- public/javascripts/lib/*.js
- public/javascripts/views/**/*.js
- app/views/workspace/*.jst
stylesheets:
common:
- public/stylesheets/reset.css
- public/stylesheets/widgets/*.css
workspace:
- public/stylesheets/pages/workspace.css
empty:
- public/stylesheets/pages/empty.css
Let's consider a case when view specific javascript should be executed only on certain view:
$(function(){
alert("View specific message here!");
}
How can I avoid such effect?
Regards,
Alexey Zakharov
My preference is to wrap up that "view-specific-javascript" in a function. And then call that function depending on the page you actually load. In this way, all of your JavaScripts can be cached by browsers as a single file, and you can execute the portions of the JS that you need.
So I'd add a <script> tag to the particular html.erb template that calls your view-specific function on page load.
Hope that helps...
I'm digging this up to point out an alternative to jashkenas approach, which is to link behaviour just to specific tags.
$(function() {
$('#my-view-object').someBehaviour();
}
So, what's the catch? The main difference is that JS code tends to be linked to certain objects, not pages. In case you reorganize your views, you will to have to change your JS too. The other problem is that JS needs to be at the bottom of the page to squeeze the most out of the browser. If you are putting script entries in your views, then most likely they will end up being all over the page's html markup and slowing the rendering.
BR,
-- José

Categories

Resources