I have a code blocks that repeat themselvs.
By writing code blocks I meen html, javascript and css that repeats in many pages.
for example:
.filter {
background-color:black;
}
$(document).ready(function(){
$('[name=aaclick]').click(function(){ alert('aa!'); });
});
<div class="filter">
aaa<input type="text" />
<a name="aaclick">click</a>
</div>
Can I combine those 3 parts of single unit together?
How can I prevent myself from writing this code again and again in different pages?
Can I combine those 3 parts of single unit together?
You can make them closer to each other (reduce number of parts to 2, at least), but I wouldn't recommend that. Styles should stay with styles, javascript with javascript and html with html.
How can I prevent myself from writing this code again and again in different pages?
1. Put this style definition in a common css file, included in every page. Do not repeat.
2. Put this javascript code in a common js file, included in every page. Do not repeat.
3. You can reduce third part to <div class="filter"></div>, if you generate the rest of the content from javascript. Something like this
$(document).ready(function(){
$('.filter').each(function() {
$(this).append('aaa').append($('<input/>').attr('type', 'text'));
...
$(this).find('input[name=aaclick]').click(...);
})
});
Now, you can put only <div class="filter"></div> in html, the rest will be autogenerated.
You probably need some templating tools.
One way would be to split them into a css, js and html file, named appropriately so you know they are related.
Then use code to add them to your page, using a standard method, thus allowing you to keep the functionality together.
In case of ASP.NET simply build user control, put the whole "repeated" block as-is in the .ascx file then wherever you need it to appear have <UC:MyBlock runat="server" /> and that's it - reliable in 100%, flexible.. really no reason to mess around with client side templates, jQuery plugins and such.
Related
I have a multi-page HTML site with common code that is reused on each page (for example, navbar code, Analytics, stylesheet imports, etc).
Is there a way to dynamically insert that common code in a manner that achieves the same result as PHP's include capability, and makes the code easier to maintain?
I've seen similar questions but not all seem to speak to what I want to achieve with the site I am working with. For example:
How to inject HTML banner code using Vanilla Javascript? - Stack Overflow
Important: Much of the code I want to insert/import will be <header> code that is necessary to properly render the pages so it will need to be inserted as the page loads.
Any suggestions? Please limit suggestions to vanilla JavaScript. I don't know JQuery at this point and want to try do this with JS.
There are a handful of ways to do what you want, but I think a template engine such as EJS or similar will meet your needs.
Do keep in mind though the implications of doing this client-side. Crawlers and such that don't run JavaScript won't have the benefit of seeing what's supposed to be on your page.
What you should probably be doing instead is running these JavaScript templates server-side, outputting static pages which then can be put on your web server or CDN.
Webpack? You could use a packaging system to fuse all your JS into one file, same for CSS. That way you have only only script and one link to add to each page. But for HTML parts, they would be added with javascript ajax and that shouldn't be a solution...
Why would you have multiple pages at all? Cant you just have one page, then update a certain ( the main part) part of your page with new code content instead of a redirect. ( if you want to see this in action visit http://google.com, http://twitter.com and many many more ). the index.html would then look like this:
<body>
<div id = "nav" >
<a href = "/whatever.html" class = "redirect" > Whatever </a>
</div>
<div id = "main" >
Some content
</div>
<script>
//embed jquery
$(_ => {
$(".redirect").on("click",function(e){
e.preventDefault();
$("#main").load(this.href);
});
});
</script>
In an ASP.NET Core app, I've a dashboard with widgets. Every widget has its own PartialViews, so the full page is generated in the following way:
-Layout.cshtml
--Dashboard.cshtml
--- Widget1.cshtml
--- Widget2.cshtml
Following best practices according to fast page load times, JavaScript is loaded before the closing </body> tag in Layout.cshtml. After that, there is a section for custom JS, which I commonly use to initiate objects on page load. So this section looks like this:
<script asp-append-version="true" type="text/javascript" src="~/clientscript/page.min.js"></script>
#RenderSection("Js", required: false)
In my Views, which are using the Layout.cshtml as layout (in this example, its Dashboard.cshtml), I can define a section like
#section Js {
// Js Code here
}
which is rendered after the script tag containing all script files. So I can be sure, that all dependencies like jQuery or custom classes are avaliable here.
But I also need to do this in widgets like Widget1.cshtml for example. The problem is: I load the PartialView Widget1.cshtml in Dashboard.cshtml. In the documentation is written, that this is not possible:
If you declare a Razor section in a partial view, it will not be visible to its parent(s); it will be limited to the partial view.
But that's exactly what I need. Is there a way to work around this limitation? Shortly, the goal is to inject JavaScript from a PartialView to the LayoutView, with an regular View between them.
The only way I know is the usage of setInterval() with a low interval like 50ms, and check there if jQuery or some of my custom class is defined in a loop until they are. Its a JS solution yes. But it makes it possible to include the script-block directly in the PartialView without making usage of sections. It fits well when you depend on a single variable like jQuery.
But I need to wait for custom classes to get loaded. They're included after jQuery. So writing a generic function like waitForTypeLoaded(type, callback) is not possible. It would cause me to write always the raw setInterval() code, which seems not a smart solution for me.
Something I did to get my scripts to run after Jquery was done loading was in my Partial Views and View Components I used the "DOMContentLoaded" event to load all my jQuery js script after the page was done loading. That way I could defer the Load of jQuery and Still Have jQuery code on my pages.
<script>
window.addEventListener('DOMContentLoaded',
function() {
$('body')....
});
</script>
Your problem can be solved as mentioned in my answer to this post:
How to render scripts, generated in TagHelper process method, to the bottom of the page rather than next to the tag element?
To sum up, you can create a pair of tag helpers, one that can be located in a partial view and just stores its content in a temporary dictionary, and the other that renders the content at the appropriate position (e.g. in the layout page). I use it extensively to render small dynamically created scripts as the final scripts of the body.
Hope it helps.
Honestly, I would make one step back and look at architecture once again if you have such dilemmas.
Why not add to required scripts which will be used on a couple of views/partial views to the main layout? In ASP.NET MVC you can use bundling mechanism (or you can write our own) - minify and bundle them with other required. It won't be heavy...
Your approach looks like unnecessary complicated.
I have some HTML files, and each one of them I want to partially render in another HTML file, for example header.html and footer.html in order to observe DRY concept.
HTML files should look like this:
<!--render header.html-->
<div>
Content
</div>
<!--render footer.html-->
How can I do that?
If you're just using plain HTML and Javascript, you could include jQuery and use an AJAX request to load the contend of another HTML page in your main page.
Have a look at the jQuery 'load()' function here:
http://api.jquery.com/load/
Assuming your have the following html:
<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>
your usage would look something like this:
$('#header').load('header.html');
$('#footer').load('footer.html');
Here's a link (first one from Google I might add) that explains how to do this in various languages.
Also note that some IDEs take care of this for you. Dreamweaver being one example; in ASP.NET there are master pages; and so on.
PHP:
<?php
require($DOCUMENT_ROOT . "path to file/include-file.html");
?>
ASP:
<!--#include file="path to file/include-file.html"-->
JS:
JavaScript is another way to include HTML within the pages of your
site. This has the advantage of not requiring server-level
programming. But it's a little more complicated than the server-level
include methods.
Save the HTML for the common elements of your site to a JavaScript
file. Any HTML written in this file, must be printed to the screen
with the document.write function.
Use a script tag to include the
JavaScript file on your pages.
<script type="text/javascript" src="path to file/include-file.js">
Use that same code on
every page that you want to include the file.
PLEASE NOTE that the JS version is NOT ideal.
1. JS may be disabled or unavailable in the browser.
2. The page won't be rendered/loaded all at once.
Also, I don't think DRY really counts for this one. Consider using an IDE that will create page templates for you (like Dreamweaver for example).
If you are brave enough (and a little bit old fashioned) and you can't use any of the above, consider using an iframe for your content:
<html>
<body>
<div>my header</div>
<iframe src="mycontent.html" />
<div>my fooder</div>
</body>
</html>
DISCLAIMER
I would rather cut off my own hands than implement the iframe or JS approach. Give deep consideration towards whether you actually NEED to do this.
If you are looking for a client side only solution that is html/js only you should have a look at AngularJS and its ngInclude syntax.
http://docs.angularjs.org/#!/api/ng.directive:ngInclude
If you are using server-side programming, you can use server-side include else if your host file is an HTML file then you can use html SCRIPT tag to include the header.html and footer.html files. Though, am not sure as to what do you really mean by partially rendering HTML file?
As others said, it looks like it can't be done with HTML alone. Another way it could be done on the server-side, if you are using Java, is with Thymeleaf.
For example, adding a main menu on every page with
<div th:replace="fragments/mainmenu.html"></div> . Then mainmenu.html could just contain a bunch of divs. The fragment doesn't need to be a full HTML page.
I am building a website using PHP and JavaScript, and I feel that I have a good grasp on where to include my JavaScript, but a more specific situation has come up that has me confused. I currently have all of my JavaScript in one external file, which is being included on every PHP page.
Let's say that I have a paragraph with an id='myParagraph' and I need to highlight this paragraph in red with JavaScript on page load. This paragraph is only on ONE PHP page and my website has about 50 different pages. I immediately assumed that I should throw some code into my one external JavaScript file, something like:
$('#myParagraph').css('color', 'red')
and the paragraph would be highlighted when that page loads.
My question is: is this the best way to do it? To my understanding, every time I load a page it will be searched for an element with the id myParagraph, yet 98% of my pages won't even have that id. Is this wasteful? Should I instead include the following code:
function highlightParagraph()
{
$('#myParagraph').css('color', 'red')
}
in my one JavaScript file and then put some inline JavaScript in the PHP file with the id myParagraph to call the function highlightParagraph() when it's loaded? That way, only the one page with myParagraph will be searched and highlighted.
I feel like option 2 is the best, but I read all the time not to use inline JavaScript.
edit: I realize that for this example you would just use CSS. I'm just using it to get my question across
You should have a one "big" js file with the infrastructure functions and all the pages should have a reference to it.
Then each page should reference another js file with the functions related only.
The good things about using external js files are:
The files are cached after the first download => Faster surfing.
Separate of concerns, you keep the presentation tier away from the scripting tier.
Another important note:
The best way to change css is with css... not javascript.
I
If you change the element style on DOM ready, just add the element definition
#myParagraph{color: red;}
The problem with inline JavaScript is you might be starting with a few lines now, but in a few weeks or months, it will add up and be a lot of inline JavaScript.
That is bad, because inline JavaScript can't be cached by the browser like JavaScript files that you include with <script src="path/to/file.js" />.
That's bad because you add a lot of content that will be fetched every single page view by the user, adding load on your server bandwidth and slowing page load for the user.
If it's just a few selectors, don't worry; The time wasted on it won't cause any browser to sweat.
Though, if it becomes a lot of code for a different page/module of your site, you might want to split it into a different JavaScript file and include just that file when certain pages are loaded.
That way, the browser will cache that file and save that bandwidth for you and the user.
I wouldn't be too surprised if many people disagree with me (violently even) but I don't have a problem with putting a javascript tag with specific javascript for that page in the header if it will reduce the number of files or overall complexity of the project. Most of the core things that are done everywhere should of course be separated in another file but if it is a one page deal, then I would go for cleanliness.
The same goes for css, if it is specific to that page just put a css tag in the header with the specific changes that differ from the master css file. BTW as everyone is pointing out, this is a case where you want to just use CSS.
I have links that when the user clicks them, the page immediately updates by utilizing the DOM, this is what my o2() does.
Problem is I want to seperate content from logic... i.e., i would prefer the content below to be in a .html file. Currently it is in a .js file.
My understanding is that it is good practice to keep structure/content seperate from logic... For example, using advanced registration for Javascript functions as opposed to inline registration.
How do I get the html content below into a .html file?
function l1() {
o2('Ac1_3','<br/><p class="h">ALL YOUR BOOKMARKS IN ONE PLACE</p><img class="i1" src="i3.jpg" alt=""/><img class="i1" src="i4.jpg" alt=""/>');
}
If you're dynamically adding stuff to the DOM using JavaScript, there is no way around keeping that content in the JS file, unless you want to get pointlessly complex.
Personally, I think it's fine to mix content and logic a little, like this, just don't go over the top to the point where it gets confusing.