MVC where to put js reference for our cshtml file? - javascript

In our existing web application we have done it at the starting of .cshtml page:
#using Carwale.UI.PresentationLogic;
#model Carwale.Entity.ViewModels.HomeModel
#{
ViewBag.CustomJS = "~/Views/StaticPartials/HomeScripts.cshtml";
ViewBag.CustomCSS = "~/Views/StaticPartials/HomeCss.cshtml";
}
And in our "~/Views/StaticPartials/HomeScripts.cshtml", we have:
#model Company.Entity.ViewModels.HomeModel
<script>var landingPage = true;</script>
<script type="text/javascript" src="#(!string.IsNullOrWhiteSpace(ViewBag.staticUrl) ? "http://st.com" + ViewBag.stagingPath : "")/js/home.js?201605021628098010"></script>
I am getting render blocking javascript suggestion from various performance website.
Can I improve this somehow?
I read that this should be in some javascript section on the bottom of the page to improve the page load time.

I would recommend you use sections within MVC. Here is another article explaining the use of sections.
Here is an example:
If you have a master layout file, that defines all of your main layouts for the website, do the following. Place this within your body tag of your master layout.
#RenderSection("scripts", false)
Then, every page/view there after that "inherits" from this master layout file, you can use this section to add your Javascript references, as follow:
#section scripts{
Scripts.Render("~/Scripts/YourCustomFolder/SomeJSFile.js")
}

When browsers hit a script tag they will stop page rendering until the script is downloaded, parsed and executed.
A best practice is to include script references just before the closing body tag. This allows the browser to download and start rendering the page markup as soon as possible without waiting for scripts.

For me the best place to add all JavaScript is almost at the end of the HTML document. Just before I close off the body tag I insert all Javascipt references and Javascript custom code. I would first like to see my HTML code get loaded and then Javascript-related stuff after this. Loading Javascript can take a while, so it is best to load it last on the page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>#ViewBag.MetaTitle</title>
#Styles.Render("~/bundles/css")
</head>
<body>
#RenderBody()
#Scripts.Render("~/bundles/js")
#RenderSection("scripts", false)
</body>
</html>
I normally first add a reference to the Javascript libraries:
#Scripts.Render("~/bundles/js")
And then I add all my custom Javascript code after I have referenced these libraries:
#RenderSection("scripts", false)
Where in your .cshtml page you "inject" your custom Javascript code probably doesn't matter. I normally first add all of my HTML code and then at the bottom of my view I will add my Javascript code like this:
<h1>Test Page</h1>
<p>Test page paragraph</p>
#section scripts {
<script>
</script>
}
I hope this helps.

Related

Can I load JavaScript Functions on One page then redirect to another?

I have an old application that I can not modify in anyway including editing the HTML in anyway directly. I had to create a redirect html page for people to load in order to always get everyone to the correct location.
Can I load a JavaScript on Page one, and keep it loaded?
I.E.
<html>
<head>
<script type="text/javascript">
function getMyAppProductID()
{
//Do the Java action to find the Product ID.
}
</ script>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<META http-equiv="refresh" content="0;URL=http://MyAppURL.internalUrl.local/StartupScript.jsp">
<title>Load...</title>
</head>
<body>
<p>Loading My App</p>
</body>
</html>
Then when I am looking at my application I want to be able to call the function I wrote.
IE. I have a floating button that does the getMyAppProductID Function.

Adding an external JavaScript file in NetBeans and linking with the index file

I have added a JavaScript file into my existing project and referred that in the HTML file. The file structure is shown as its in the attachment. After I run the program, the output does not display what it is supposed to be.
Is there anything wrong with my file tree (how I am adding file into the project) or I am not referring the script the in the correct way?
Here is how my program looks like:
index:
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="newjavascript.js" type="text/javascript"></script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
.JS:
document.getElementById("demo").innerHTML = 7+9;
It seems to be everything is ok with your project structure and refererring to js file inside index.html. However, the demo paragraph does not display what you want because it can be just not loaded in the time when your newjavascript.js is executed. I think you can try to modify it in the following way:
window.onload = function () {
document.getElementById("demo").innerHTML = 7+9;
};
Using onload function of window object you wait until a page (including demo paragraph) is loaded - and after it change its content.

Script tags - not linking (JS platform game)

I'm working through the 'create a platform game' project from Eloquent JavaScript and have an issue with script tags.
In the book we're told to display our level using:
<link rel="stylesheet" href="css/game.css">
<script>
var simpleLevel = new Level(simpleLevelPlan);
var display = new DOMDisplay(document.body, simpleLevel);
</script>
I've tried adding this (together with an additional script tag for my platform.js file) into index.html but the browser is giving nothing back, not sure what I'm doing wrong?
Ensure you are inserting your scripts in the right order:
<!DOCTYPE html>
<html>
<head>
Here you should put your "included" scripts with <script src=...>
</head>
<body>
...
</body>
<script>
Here you should put your first execution, if it needs the html page been completely loaded (as to use document.body).
</script>
</html>
The scripts are being executed as they appear into the page. If you use document, you have to delay the execution until the whole page has been loaded: Either by putting your script at the end of the HTML, either by putting an initialization function within the HEAD, and call it from body onload:
<head>
<script>
function myFunction(){...}
</script>
</head>
<body onload="return myFunction()">
...
</body>
Make sure to include the external JavaScript file you need in a separate <script> tag before your inline script!

Accessing jQuery within a JavaScript namespace / module pattern [duplicate]

So classic problem, but having a horrible time on finding the actual cause. Typically when I see this error it's because the jQuery reference is after code requiring it, or back jQuery link, or jQuery conflict, etc... so far none of those appear to be the case. Unfortunately seeking out the solution to this problem has lead me to post after post of such cases. I'm sure my problem here is equally as simple, but over an hour of hunting, still no luck...
Edit: Additional information...
The solution file (which I've recreated multiple times trying to figure this out. Is a JavaScript Windows Store Blank App template and I'm doing this in Visual studio. The only references files is Windows Library for javascript 1.0, I have tried deleting this to test as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Template</title>
<style>
/* styles here */
</style>
</head>
<body>
<canvas id="myCanvas" width="500" height="500">
<p>Canvas not supported.</p>
</canvas>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var canvas = $("#myCanvas").get(0);
var context = canvas.getContext("2d");
function renderContent()
{
// we'll do our drawing here...
}
renderContent();
});
</script>
</body>
</html>
It's states that JQuery referred URL is not correct
Try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
I tried everything listed above and nothing seems to work until I put this string
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
in the head section of the HTML file. So here's how it looks:
<!DOCTYPE html>
<html>
<head>
<!-- jQuery Reference -->
<script src="../scripts/jquery-2.2.3.min.js" type="text/javascript"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<title>some title</title>
</head>
<body>
...
And the js file is located at a level below in the folder 'scripts'.
Finally, the error is gone and what a relief!
In my case, the problem was that I was rendering my page over https but I was trying to request the JQuery file over http, which is blocked by many browsers for security reasons.
My fix was to change this...
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
...to this...
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
This causes the browser to download JQuery using the same protocol (http or https) as the page being rendered.
Some of my clients had this problem, because apparently they blocked loading Javascript from 3rd party sites. So now I always use the following code to include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
window.jQuery ||
document.write('<script type="text/javascript" src="/js/jquery-1.9.1.min.js">\x3C/script>')
</script>
This makes sure, that even if my client blocks loading the Javascript file from the CDN domain, the client still downloads the file from my own server, which is not blocked by the browser.
Anover variant, in my case - I was forced to use proxy. So - IE11--> InternetOptions --> Connections-->LANSettings-Proxy Server--> UseProxyServer - should be checked.
Also check awailability of jQUery script source, my worked variant in VS2012 - -just like in top example
I was getting this same error code:
(Error: 'generateText' is undefined)
...on the code
var bodyText=["The....now."]
I discovered on my text-editor(Notepad++), when typing many lines of text in the directly above the variable bodyText, if I didn't hit return carriage (enter==>WordWrap is off) just kept typing w/o return carriage and let the editor adjust text it worked?
Must be in the settings of Notepad++??

How does the location of a script tag in a page affect a JavaScript function that is defined in it?

I read that you should define your JavaScript functions in the <head> tag, but how does the location of the <script> (whether in the <head>, <body>, or any other tag) affect a JavaScript function.
Specifically, how does it affect the scope of the function and where you can call it from?
Telling people to add <SCRIPT> only in the head sounds like a reasonable thing to do, but as others have said there are many reasons why this isn't recommended or even practical - mainly speed and the way that HTML pages are generated dynamically.
This is what the HTML 4 spec says :
The SCRIPT element places a script
within a document. This element may
appear any number of times in the HEAD
or BODY of an HTML document.
And some sample HTML. Doesn't it look pretty all formatted here :)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>
And something to look forward to in HTML 5 :
New async attribute in <SCRIPT> :
Note: There are ways [sic] a script can be
executed:
The async attribute is "true": The
script will be executed asynchrously
with the rest of the page, so the
script will be executed while the page
continues the parsing.
The async attribute is "false", but
the defer attribute is "true": The
script will be executed when the page
is finished with the parsing.
The normal rules of play still stand; don't use stuff before it's defined. :)
Also, take note that the 'put everything at the bottom' advice isn't the only rule in the book - in some cases it may not be feasible and in other cases it may make more sense to put the script elsewhere.
The main reason for putting a script at the bottom of a document is for performance, scripts, unlike other HTTP requests, do not load in parallel, meaning they'll slow down the loading of the rest of your page. Another reason for putting scripts at the bottom is so you don't have to use any 'DOM ready' functions. Since the script tag is below all elements the DOM will be ready for manipulation!
EDIT: Read this: http://developer.yahoo.com/performance/rules.html#js_bottom
One of the aspects of placement is performance. See this fine article within the YSlow discussion for why it's sometimes recommended you put them at the bottom of the document.
As for issues of scope, the usual visibility rules for Javascript (vars defined inside or outside of functions, local, global, closures, etc.) are not affected so far as I know.
Position of script tag does matter.
If you bind a Function with document Element then the document element has to be loaded first before we implement function. suppose getTeachers() is function in getTeachers.js file.
This will give you an error:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<span id="results" /></span>
</body>
</html>
It gives error before head is loaded first and it cannot find element with id specified.
The below code is correction:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
<span id="results" /></span>
</body>
</html>
If your script refers to an ID on the page and the page has not been rendered (i.e. script is before HTML, or your script is executed with onload, rather then the DOM is ready) you can also get an error.
It doesn't. Most programming framework scatter scripts all throughout the page. I've only rarely seen problems because of that (and only from older browsers).
If you pull Javascripts in through XMLHttpRequest, like Diodeus said, it probably won't work. In my case, there was no error, the browser just ignores the new script(s).
I ended up using this, not terribly elegant but works for me so far:
http://zeta-puppis.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/
How to use execJS: http://zeta-puppis.com/2006/02/23/javascript-script-execution-in-innerhtml/
Note: Watch out for < in this line: for(var i=0;i<st.length; i++)
If you have an inline script (outside functions) located before functions it may call, you may get an error because they may not be not available yet. Not saying it is always going to happen, just that it may depending on browser type or version.
Javascript's scoping rules are similar to perl - you can call any function at the current or any higher scope level. The only restriction is that the function has to be defined at the time you call it. The position in the source is irrelevant - only the position in time matters.
You should avoid putting scripts in the <head> if possible as it slows down page display (see the link Alan posted).

Categories

Resources