What is the javascript equivalent to PHP's include(file.html) specifically without needing to place it in a div like $("#div").load("file.html");? I'd like to get away from using PHP and find out how to do this in Javascript without using a div placeholder and just loading it into webcode to use with things like bootstrap modals or buttons.
in this case, php acts as a preprocessor - it sees that include line, fetches the html and then drops the contents of the file in-place. Javascript can't really do that in the same way because it only lives on the browser.
You have some options
Do you an http request to a resource that will return the html, and then render that html string to a location (html id tag of some sort)
Use a different preprocessor. There's loads and it depends on what runtime you're on. NodeJS? Ruby? Go? Java? Python? All of them use something different - but they'll give you a one-to-one alternative for the directives you want to use inside your html files. Here's a great article that gives an overview of a number of different options: https://css-tricks.com/the-simplest-ways-to-handle-html-includes/
naturally, when you want to load a resource from js (when it is possible and do not try to access a resource that triggers a cross domain origin problem) you use AJAX
a simple implementation using jQuery:
$.get('file.html', function(file) {
console.dir(file);
});
Related
Just a quick question here. I am trying to register a js file for script validation using
if (!Page.ClientScript.IsClientScriptBlockRegistered("strIncludeJSFile")) Page.ClientScript.RegisterClientScriptBlock(strIncludeJSFile.GetType(), "strIncludeJSFile", strIncludeJSFile);
code in C# and it works well for the js files. But, some js files are used in multiple pages, so I am unsure if the above code will be a good idea. As such, I want to do the same thing in the js file itself, instead of using the code behind. Is there any possibility to do that? Or is this thing specific to C#?
of course you can register a js file (or script block) from html by using a script tag. However, the main reason RegisterClientScriptBlock exists is because developers might need to generate (or modify) a script block dynamically from code behind or conditionally register a script file dynamically.
If you need any of the above...generate a script block dynamically, then you "might" be better off registering it from code behind, I mean, it depends on the whole solution itself, it's hard to recommend an approach without having some context. Either way, some options are:
register the script blocks from code behind if you need to generate based on some conditions that can only be evaluated from server side code
use a master page for better and register the script block from the master page. This will make it easier to maintain if you keep the logic in one place
similar to the option above, you can use a base page class if using a master page is not possible
use an html script element if what you need is to reference a static js file
use place holders such as js variables and fetch dynamic data from the server using ajax
use unobtrusive javascript, custom data attributes and ajax
Whatever the suitable option(s) is depends on too many factor that you have to assess
We have some widgets developed using Dojo and Javascript. The dojo code invokes some application services using io script mechanism to overcome cross browser issues. Currently the action for the io script is hard coded as follows.
var host="myhost.com";
var url = "http://"+host+"/context/service";
Every time we need to create WAR, we have to change host details. Is there a way in JS we can configure this ie., some thing like reading it from properties.
I found this s:url struts tag. I assume we can use this tag inside javascript code in a JSP. Can i use it in plain JS out side of JSP?
Sure, if you have your container set up to process *.js files as JSP files.
IMO this is a bit brittle.
You can also do things like hide data in the DOM via hidden elements or <script> tags with reasonable type attributes (e.g., not "text/javascript", the default).
You can also put the data into JavaScript variables in the JSP and access them from external JS files.
Currently I am creating a website which is completely JS driven. I don't use any HTML pages at all (except index page). Every query returns JSON and then I generate HTML inside JavaScript and insert into the DOM. Are there any disadvantages of doing this instead of creating HTML file with layout structure, then loading this file into the DOM and changing elements with new data from JSON?
EDIT:
All of my pages are loaded with AJAX calls. But I have a structure like this:
<nav></nav>
<div id="content"></div>
<footer></footer>
Basically, I never change nav or footer elements, they are only loaded once, when loading index.html file. Then on every page click I send an AJAX call to the server, it returns data in JSON and I generate HTML code with jQuery and insert like this $('#content').html(content);
Creating separate HTML files, and then for example using $('#someID').html(newContent) to change every element with JSON data, will use even more code and I will need 1 more request to server to load this file, so I thought I could just generate it in browser.
EDIT2:
SEO is not very important, because my website requires logging in so I will create all meta tags in index.html file.
In general, it's a nice way of doing things. I assume that you're updating the page with AJAX each time (although you didn't say that).
There are some things to look out for. If you always have the same URL, then your users can't come back to the same page. And they can't send links to their friends. To deal with this, you can use history.pushState() to update the URL without reloading the page.
Also, if you're sending more than one request per page and you don't have an HTML structure waiting for them, you may get them back in a different order each time. It's not a problem, just something to be aware of.
Returning HTML from the AJAX is a bad idea. It means that when you want to change the layout of the page, you need to edit all of your files. If you're returning JSON, it's much easier to make changes in one place.
One thing that definitly matters :
How long will it take you to develop a new system that will send data as JSON + code the JS required to inject it as HTML into the page ?
How long will it take to just return HTML ? And how long if you can re-use some of your already existing server-side code ?
and check how much is the server side interrection of your pages...
also some advantages of creating pure HTML :
1) It's simple markup, and often just as compact or actually more compact than JSON.
2) It's less error prone cause all you're getting is markup, and no code.
3) It will be faster to program in most cases cause you won't have to write code separately for the client end.
4) The HTML is the content, the JavaScript is the behavior. You're mixing both for absolutely no compelling reason.
in javascript or nay other scripting language .. if you encountered a problem in between the rest of the code will not work
and also it is easier to debug in pure html pages
my opinion ... use scriptiong code wherever necessary .. rest of the code you can do in html ...
it will save the triptime of going to server then fetch the data and then displaying it again.
Keep point No. 4 in your mind while coding.
I think that you can consider 3 methods:
Sending only JSON to the client and rendering according to a template (i.e.
handlerbar.js)
Creating the pages from the server-side, usually faster rendering also you can cache the page.
Or a mixture of this would be to generate partial views from the server and sending them to the client, for example it's like having a handlebar template on the client and applying the data from the JSON, but only having the same template on the server-side and rendering it on the server and sending it to the client in the final format, on the client you can just replace the partial views.
Also some things to think about determined by the use case of the applicaton, is that if you are targeting SEO you should consider ColBeseder advice, of if you are targeting mobile users, probably you would better go with the JSON only response, as this is a more lightweight response.
EDIT:
According to what you said you are creating a single page application, if this is correct, then probably you can go with either the JSON or a partial views like AngularJS has. But if your server-side logic is written to handle only JSON response, then probably you could better use a template engine on the client like handlerbar.js, underscore, or jquery templates, and you can define reusable portions of your HTML and apply to it the data from the JSON.
If you cared about SEO you'd want the HTML there at page load, which is closer to your second strategy than your first.
Update May 2014: Google claims to be getting better at executing Javascript: http://googlewebmastercentral.blogspot.com/2014/05/understanding-web-pages-better.html Still unclear what works and what does not.
Further updates probably belong here: Do Google or other search engines execute JavaScript?
I'm thinking of doing some online file manipulation for mobile users, the idea being that the user provides a URL to the file, then the file contents are modified by the JS, and can then be downloaded. But I haven't been able to figure out how to get the file when it's on a separate domain using just JS.
Is this possible? If so any hints or examples would be appreciated.
Just wanted to add that part of what I wanted to do was make it available without my hosting it. I'm thinking of something like a a file they can host somewhere,and then all of the bandwidth is their own...and that of wherever they are getting the file from of course.
The only way to load contents of a file on another domain is from within a <script> tag. This is how JSONP works. Look into getting your target file into this format.
The other way would be to use a local proxy. Create a web service method that loads and returns the contents of the file, then call that locally using your favorite JavaScript framework.
Depending on how you think of public webservices, and within some limitations I'm still mapping, you can do this using an ajax call to YQL, like so.
(will expand the answer later).
http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20data.uri%20where%20url=%22http://t3.gstatic.com/images?q=tbn:ANd9GcSyART8OudfFJQ5oBplmhZ6HIIlougzPgwQ9qcgknK8_tivdW0EOg%22
One of the limitations of this method is file size, it currently tops out at 25k.
I'm usually a creative gal, but right now I just can't find any good solution. There's HTML (say form rows or table rows) that's both generated javascript-based and server-sided, it's exactly the same in both cases. It's generated server-sided when you open the page (and it has to stay server-sided for Google) and it's generated by AJAX, to show live updates or to extend the form by new, empty rows.
Problem is: The HTML generation routines are existing twice now, and you know DRY (don't repeat yourself), aye? Each time something's changed I have to edit 2 places and this just doesn't fit my idea of good software.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
PS: Server-sided language is always different (PHP, RoR, C++).
PPS: Please don't give me an answer for Node.JS, I could figure that out on my own ;-)
Here's the Ruby on Rails solution:
Every model has its own partial. For example, if you have models Post and Comment, you would have _post.html.erb and _comment.html.erb
When you call "render #post" or "render #comment", RoR will look at the type of the object and decide which partial to use.
This means that you can redner out an object in the same way in many different views.
I.e. in a normal response or in an AJAX response you'd always just call "render #post"
Edit:
If you would like to render things in JS without connecting to the server (e.g. you get your data from a different server or whatever), you can make a JS template with the method I mentioned, send it to the client and then have the client render new objects using that template.
See this like for a JS templating plugin: http://api.jquery.com/category/plugins/templates/
Make a server handler to generate the HTML. Call that code from the server when you open the page, and when you need to do a live update, do an AJAX request to that handler so you don't have to repeat the code in the client.
What's your best strategy to combine the javascript-based and server-sided HTML generation?
If you want to stay DRY, don't try to combine them. Stick with generating the HTML only on the server (clearly the preferable option for SEO), or only on the client.
Make a page which generates the HTML on the server and returns it, e.g.:
http://example.com/serverstuff/generaterows?x=0&y=foo
If you need it on the server, access that link, or call the subroutine that accessing the link calls. If you need it on the client, access that link with AJAX, which will end up calling the same server code.
Or am I missing something? (I'm not sure what you mean by "generated by AJAX").
I don't see another solution if you have two different languages. Either you have a PHP/RoR/whatever to JavaScript compiler (so you have source written in one language and automatically generated in the others), or you have one generate output that the other reads in.
Load the page without any rows/data.
And then run your Ajax routines to fetch the data first time on page load
and then subsequently fetch updates/new records as and when required/as decided by your code.