Accessing Javascript globals from aspx page to another - javascript

Here's the underlying folder structure:
| ...
| Top.aspx
| ...
|
\---Include
...
ClientScriptGlobals.aspx
...
\---Config
...
Project.config
...
Here's a snippet of Top.aspx:
<%# Page Language="vb" AutoEventWireup="false" Codebehind="Top.aspx.vb" Inherits="Project.Top"%>
<!--DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"-->
<html>
<head><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE10" />
<title>....</title>
<META HTTP-EQUIV="imagetoolbar" CONTENT="no">
<!--#include virtual="..."-->
<!--#include virtual="Include/ClientScriptGlobals.aspx" -->
<!--#include virtual="...." -->
....
</head>
</html>
And finally ClientScriptsGlobal.aspx:
<script language="javascript">
//Globals
...
var FullTextSearchStatus = "<%= FullTextSearchStatus %>"
...
</script>
To give some context, Top.aspx includes ClientScriptGlobals.aspx so that I can access its global variables, which are also being used throughout the application.
My issue arises when I use aspnet_compiler.exe to pre-compile my application. Once it reaches ClientScriptsGlobal.aspx, it returns a bunch of errors like this:
error BC30451: Name 'FullTextSearchStatus" is not declared.
So now my question is, how can I tell ClientScriptsGlobal.aspx the location of FullTextSearchStatus's definition?
Keep in mind that when I opt to not pre-compile the application, these errors do not occur because the Javascript is not being compiled beforehand and therefore, its references have already been established (if that's the correct way describe this).

Related

Why I get error when I attach reference to js file?

I fill shame to ask this silly question but anyway I get this erorr:
Uncaught SyntaxError: Unexpected identifier
Any time that I add this ref:
<script src="../Scripts/ddd.js"></script>
to index.cshtml page.
Here is index.cshtml page:
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<script src="../Scripts/ddd.js"></script>
</head>
<body>
<div>
Home
</div>
</body>
</html>
And here is ddd.js file:
(function () {
alert("ddd")
}());
UPDATE
I use asp.net core 2.2
Any idea why I get the error above?
please add reference like this
<script src="~/Scripts/ddd.js"></script>
In ASP.NET Core default root folder is always wwwroot folder. So you need to put your files under wwwroot folder. If you want to refer that file from a regular html file you can use '''
"../Scripts/ddd.js"
'''
However if you refer it in a cshtml page with razor code then you would need
'''
"~/Scripts/ddd.js"
'''
"~" points to root folder in razor syntax.

nopcommerce 3.80 ender-blocking JavaScript and CSS in above-the-fold content

I'm using the "async" property of Html.AppendScriptParts method in nopcommerce 3.80 like that Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js",false,true);
The google PageSpeed Tools give it a high score which is i expected:
But it seems effect to the other functionalities of website (nivo slider, ajax filter which comes from Seven Spikes plugin,... )
I'm not using js and css bundling feature in nopcommerce.
Can you guys please tell me what is the best solution in my scenarior now ?
Any helps are very appriciated.
Thank you so much.
Here is my code of _Root.head.cshtml:
#using Nop.Core.Domain.Common;
#using Nop.Core.Domain.Seo
#using Nop.Core.Infrastructure;
#{
var displayMiniProfiler = EngineContext.Current.Resolve<Nop.Core.Domain.StoreInformationSettings>().DisplayMiniProfilerInPublicStore;
Html.AppendScriptParts("~/Scripts/public.ajaxcart.js");
Html.AppendScriptParts("~/Scripts/public.common.js");
Html.AppendScriptParts("~/Scripts/jquery-migrate-1.2.1.min.js");
Html.AppendScriptParts("~/Scripts/jquery-ui-1.10.3.custom.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.unobtrusive.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.min.js");
Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js",false,true);
var commonSettings = EngineContext.Current.Resolve<CommonSettings>();
if (commonSettings.RenderXuaCompatible)
{
Html.AppendHeadCustomParts(string.Format("<meta http-equiv=\"X-UA-Compatible\" content=\"{0}\"/>", commonSettings.XuaCompatibleValue));
}
var seoSettings = EngineContext.Current.Resolve<SeoSettings>();
if (!string.IsNullOrEmpty(seoSettings.CustomHeadTags))
{
Html.AppendHeadCustomParts(seoSettings.CustomHeadTags);
}
}
<!DOCTYPE html>
<html#(this.ShouldUseRtlTheme() ? Html.Raw(" dir=\"rtl\"") : null) #Html.NopPageCssClasses()>
<head>
<title>#Html.NopTitle()</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<meta name="description" content="#(Html.NopMetaDescription())" />
<meta name="keywords" content="#(Html.NopMetaKeywords())" />
<meta name="generator" content="nopCommerce" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
#Html.NopHeadCustom()
#Html.Partial("Head")
#Html.Widget("head_html_tag")
#Html.NopCssFiles(this.Url, ResourceLocation.Head)
#Html.NopScripts(this.Url, ResourceLocation.Head)
#Html.NopCanonicalUrls()
#Html.Action("RssHeaderLink", "News")
#Html.Action("RssHeaderLink", "Blog")
#Html.Action("Favicon", "Common")
#if (displayMiniProfiler)
{
#StackExchange.Profiling.MiniProfiler.RenderIncludes()
}
</head>
<body>
#RenderBody()
#Html.NopCssFiles(this.Url, ResourceLocation.Foot)
#Html.NopScripts(this.Url, ResourceLocation.Foot)
</body>
</html>
First, it's not related to Seven Spikes plugins. This issue is because of async behavior. When you make jquery file to an async, it means application will not wait to load that file and going to load next js file. But other js file are depended on first main file, and that's way you're getting errors.
Let's understand it with current scenario, the default code is:
Html.AppendScriptParts("~/Scripts/public.ajaxcart.js");
Html.AppendScriptParts("~/Scripts/public.common.js");
Html.AppendScriptParts("~/Scripts/jquery-migrate-1.2.1.min.js");
Html.AppendScriptParts("~/Scripts/jquery-ui-1.10.3.custom.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.unobtrusive.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.min.js");
Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js");
In this case the order of js files are:
Now load jquery min js file asynchronously.
Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js", false, true);
And check console:
With this change you will get an error(s).
To resolve this issue, you have to load js min file in one particular order on basis of dependency.
Side Note: this issue is with default code too!! I've tested with nopCommerce 3.80 and 3.90

Is there a nice way to route using EJS teamplate avoiding repetition with Express server?

Let's say that my app has two view: index.ejs, profile/index.ejs
I want to route using express code like below.
/* GET home page. */
router.get('/', function (req, res, next) {
res.render('index');
});
/* GET profile page. */
router.get('/profile', function (req, res, next) {
res.render('profile/index');
});
should both two ejs files have bootstrap link?
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
If the answer is yes, whenever I want to render another page, should I reload style and js file from CDN?
I mean, is there a nice way to keep common contents when I change my EJS template?
There are several ways to achieve this.
1). use partials and include them in every page.
2). If you don't like including the partials in each page then you can use express-ejs-layouts or ejs-locals
For the first approach we can have a partials directory that will contain all the partials we need.
And here are our partials
//partials/head.ejs
<meta charset="UTF-8">
<title>EJS Template</title>
<link ref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
This scipt.js can include all the scripts that you want to include.
//partials/script.js
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script>
Let's say we want to include these partials in index.ejs then all we need to do is to simply use <% include partial %> and we are good to go.
// index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<% include partials/head %>
</head>
<body class="container">
<header>
<% include partials/header %>
</header>
<main>
<div class="jumbotron">
<h1>This is great</h1>
<p>Welcome to templating using EJS</p>
</div>
</main>
<footer>
<% include partials/footer %>
</footer>
<% include partials/script %>
</body>
</html>
Hope this helps !!
No. You can do this easily by adding scripts and css that are used for whole application into different EJS file.
For example.
Create file called header.ejs and add in it all links and scripts.
Then in your templates just include this file, with this piece of code
<head>
<% include header.ejs %>
//IN HERE you can add page specific scripts or links
</head>
Hope this helps

Create pages with pre-compiling the templates

In my current project, my work is only with html and css (HTML skinning). There are many pages which have repeated sections like Header, footer, sharing links etc.
I don't want to repeat this common sections again and again in each page. I want these repeated sections to call somehow using gulp or any other task runner.
Something like this for example (using lodash)
Index.html
<!Doctype html>
<html>
<%= _.template(templates['head'])() %>
<body>
<%= _.template(templates['header'])() %>
<!-- some unique content here -->
<%= _.template(templates['footer'])() %>
</body>
</html>
and then using gulp-template rendering it in each page. I am preferring lodash because I had already worked with it.
As you can see, I am assuming that if somehow I keep the repeating sections in a javascript object (with name templates), I can call it in one line code. And then if I change something in that repeating section, the change will occur in all pages.
To make this possible, first I need to generate the javascript object with that repeating html as string in it.
Can someone please tell me how to do this? or is there any better way to do this?
You can use Jade - node template engine
It gives option to include external jade files, where in it allows you to insert the contents of one jade file into another
index.jade:
doctype html
html
include ./includes/head.jade
body
h1 My Site
p Welcome to my super lame site.
include ./includes/foot.jade
head.jade
//- includes/head.jade
title My Site
script(src='/javascripts/jquery.js')
script(src='/javascripts/app.js')
foot.jade
//- includes/foot.jade
#footer
p Copyright (c) foobar
Compiles to:
index.html
<!doctype html>
<html>
<head>
<title>My Site</title>
<script src='/javascripts/jquery.js'></script>
<script src='/javascripts/app.js'></script>
</head>
<body>
<h1>My Site</h1>
<p>Welcome to my super lame site.</p>
<div id="footer">
<p>Copyright (c) foobar</p>
</div>
</body>
</html>
Explanation:
Whenever I used to search on google for "pre-compiling templates", I was ending up on sites which were combining all the HTML template files to one single js file. But in my case, I was looking for a way to compile the templates completely on system itself with no support of a "all template compiled js file". (So, I was looking for a solution which pre-renders the HTMLs)
Solution:
I found this awesome template engine, Nunjucks, which lets me compile the HTML templates to Independent HTML pages when used with gulp.
Check this one, gulp-nunjucks-render. By using this along with gulp, I am able to include section of .html files into other .html files. Here is the code (assuming you installed nodejs and gulp):
var gulp = require('gulp');
var nunjucksRender = require('gulp-nunjucks-render');
gulp.task('default', function () {
nunjucksRender.nunjucks.configure(['templates/'], { watch: false });
return gulp.src('templates/!(_)*.html')
.pipe(nunjucksRender({
css_path: "../assets/css/",
js_path: "../assets/js/",
img_path: "../assets/images/"
}))
.pipe(gulp.dest('html'));
});
gulp.task('watch', function () {
gulp.watch(['templates/*.html'], ['default']);
});
In the above code, I am keeping the HTML templates in templates folder and with the above gulp code, I am generating the new HTMLs in html folder. The above code will not generate the files which are prefixed with _. (something similar to sass)
and later in command prompt:
gulp watch // Watches the files for changes continuously --> OWNING :D
Here is an example:
<!-- // Index.html -->
<!DOCTYPE html>
<html>
{% include "_head.html" %}
<body>
{% include "_content.html" %}
{% include "_footer.html" %}
</body>
</html>
Which renders to:
<!DOCTYPE html>
<html>
<head>
<title>Website title</title>
<link rel="Stylesheet" href="../assets/jcss/main.css" type="text/css"/>
</head>
<body>
<div class="page">
<!-- content here -->
</div>
<div class="footer">
<!-- footer content here -->
</div>
</body>
</html>
Advantages:
No need of server support to compile the templates.
No need to include any pre-compiled js file in index.html.
Whenever we do some change in common section, no need to include that section again in every page.
Disadvantages:
Till now, I didn't find any :).

Unobtrusive JavaScript - Separate JS File Not Found

Using the concept unobtrusive JavaScript, I'm trying, for the first time, to place my JavaScript in a separate file from the HTML. But, no matter what I do, I get an error that the file wasn't found.
This is the actual error in the google chrome console (ctrl-shift-j):
GET http://localhost:14385/Home/TestPage.js 404 (Not Found)
I started with a new MVC 4 app. I created a new test page:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<script src="TestPage.js"></script>
<title></title>
</head>
<body>
<div>
<input id="foo" value="snuh" />
</div>
</body>
</html>
And I created a new TestPage.js in the same folder:
$(document).ready(function() {
function dosomething() {
alert('snuh');
}
document.getElementById('foo').onclick = dosomething;
});
I've tried the tips posted here, but I always get an error that the JavaScript file isn't found. Any idea what's wrong with this simple test?
Note: The TestPage actually displays, with the input box showing.
This is the layout in solution explorer:
Make sure you reference your javascript from the correct location using server side helpers:
<script src="<%= Url.Content("~/TestPage.js") %>"></script>
This will properly reference the javascript file no matter from which location you have rendered this view. It assumes obviously that you have placed your javascript file in the root of your application. The The convention is to use the Scripts folder for this:
<script src="<%= Url.Content("~/Scripts/TestPage.js") %>"></script>
UPDATE:
Now that you have shown your project structure you seem to have placed the TestPage.js file inside the ~/Views folder. This won't work. This folder is not accessible from the client side. It is explicitly forbidden and not served by IIS. You should never place any static files inside. Move your javascript folder to the ~/Scripts folder.
Also you seem to be using jQuery inside your TestPage.js file but you never referenced it so your script won't work. If you want to use jQuery make sure that you have added it as well:
<script src="<%= Url.Content("~/Scripts/jquery-1.8.2.js") %>"></script>
<script src="<%= Url.Content("~/Scripts/TestPage.js") %>"></script>
or if you don't want to use jQuery fix your script so that it doesn't depend on it:
function dosomething() {
alert('snuh');
}
window.onload = function() {
document.getElementById('foo').onclick = dosomething;
};
or if you place your scripts at the end of your DOM you don't even need to wrap them in a document ready handler because at this stage the DOM will be ready and you can manipulate it:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
<input id="foo" value="snuh" />
</div>
<script src="<%= Url.Content("~/Scripts/TestPage.js") %>"></script>
</body>
</html>
and then inside your script:
function dosomething() {
alert('snuh');
}
document.getElementById('foo').onclick = dosomething;

Categories