newbie question about javascript embed code? - javascript

I am a javascript newbie. I am trying to write a requirements document, and need some help describing what I am looking for. We want our application to generate a javascript snippet like this:
<script src="http://www.jotform.com/jsform/10511502633"></script>
This will load a web form.
So my question is:
- How does a single script load an entire web form? Is this a JSON?
- What is this called? Is this a cross browser javascript?
- Can anyone point me in the direction of learning more about what this is?
Thank you for your help!

The javascript file is just hosted on an external site. It appears to be dynamically generated, so feel free to use some fancy words ;) But basically, you just include it here, as if it was on your own site.
You could say "The application will generate the required script-tags to include dynamically generated javascript file from an external, third-party site".
Offcourse you need to take special cautions for cases when the include won't work, because the other site is not reachable (site is down, DNS does not work, file is moved on other webserver, your application is on an intranet/behind a proxy/firewall...). Why can't you copy their file and mirror it locally? Or use a reliable Content Delivery Network, like Google or Amazon.

There are many names for this type of inclusion. The most common being widget.
What does it actually do:
take an id of some sort as parameter
use the id to fetch some specific data (most likely from a database)
generate some js and html based on the id/data
usually this involves iframes of some sort.
To use a script rather than an html iframe has multiple advantages
you can change what is actually delivered to the users browsers without changing the include
you can resize the iframe to fit certain predefined sizes
you can inject the necessary things into the page the widget is included (of course you need to make sure this is sanctioned)
We use this all the time and we never regreted it.
If you don't want to build the widget infrastructure yourself you can always use one of the widget providers like widgetbox:
http://www.widgetbox.com/widgets/make/
With those you are up and running in no time.

This is typically called a script include.

Google have lots of these types of items, and even they call them by many names,
widgets, custom javascript, snippets, custom code, etc. It really depending on who you are writing for... I would go with "cross platform embeddable javascript code" meaning that it would need to load all its dependancies. Also specify which browsers need to be supported and what should happen is the user has javascript turned off.
EDIT :
Actually since we are talking unique IDs, you will need 2 parts probably, the user/site unique "cross platform embeddable javascript code" and whatever serverside code to support it. Basically this is an API that is accessed using your own javascript widget. Feel free you point to examples in your requirements document, programmers love examples.

Related

Converting a web app into an embeddable <script> tag

I just did a proof of concept/demo for a web app idea I had but that idea needs to be embedded on pages to work properly.
I'm now done with the development of the demo but now I have to tweak it so it works within a tag on any websites.
The question here is:
How do I achieve this without breaking up the main website's stylesheets and javascript?
It's a node.js/socket.io/angularjs/bootstrap based app for your information.
I basically have a small HTML file, a few css and js files and that's all. Any idea or suggestions?
If all you have is a script tag, and you want to inject UI/HTML/etc. into the host page, that means that an iframe approach may not be what you want (although you could possibly do a hybrid approach). So, there are a number of things that you'd need to do.
For one, I'd suggest you look into the general concept of a bookmarklet. While it's not exactly what you want, it's very similar. The problems of creating a bookmarklet will be very similar:
You'll need to isolate your JavaScript dependencies. For example, you can't load a version of a library that breaks the host page. jQuery for example, can be loaded without it taking over the $ symbol globally. But, not all libraries support that.
Any styles you use would also need to be carefully managed so as to not cause issues on the host page. You can load styles dynamically, but loading something like Bootstrap is likely going to cause problems on most pages that aren't using the exact same version you need.
You'll want your core Javascript file to load quickly and do as much async work as possible as to not affect the overall page load time (unless your functionality is necessary). You'll want to review content like this from Steve Souders.
You could load your UI via a web service or you could construct it locally.
If you don't want to use JSONP style requests, you'll need to investigate enabling CORS.
You could use an iframe and PostMessage to show some UI without needing to do complex wrapping/remapping of the various application dependencies that you have. PostMessage would allow you to send messages to tell the listening iFrame "what to do" at any given point, while the code that is running in the host page could move/manipulate the iframe into position. A number of popular embedded APIs have used this technique over the years. I think DropBox was using it for example.

Organizing Javascript w/ jQuery

I am tinkering around with jQuery and am finding it very useful and almost exciting.
As of now, I am referencing the jQuery script via Google's CDN and I store plugins I use locally in a static/scripts directory.
Naturally, each page has its own individual implementation of components that are required for the features it currently offers. I.E. the main page has the Twitter plugin whereas the login page has form validation logic and password strength metering. However, certain components (navigation bar) for example use the same script across multiple pages.
Admittedly so, I am not a fan of putting javascript code in the header of a page, but I rather prefer to have it in an external file (for caching, re-usability, and optimization purposes).
My question is, what is the preferred route for organizing the external files. I wanted to try and keep it to one javascript file for the entire site to reduce IO requests. However, I am not sure how to implement document ready functions on a conditional per page bases.
$(document).ready(function () { ... }
Is there some way to reference a page by some method (preferably id based and not a url conditional).
Thank you in advance for your time!
You should try REQUIRE JS.
This will allow you to load only those plugins the pages where you need them, and unload them again if they are not needed anymore.
Then again, it might be overkill. It really depends on the size of your project.
Paul Irish:
http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/
This will allow you to block your scripts by body class/ID and execute them automatically.
First you might want to use YUI Compressor or some other JS compressing tool. Then perhaps creating a resource file (resx) for your JavaScript is the way to go. Then just reference the resource within your code. This is the approach Telerik took for their RadControl ASP.NET AJAX control framework.

Javascript in MediaWiki

I'd like to use some Javascript on my wiki pages, but I haven't been able to figure out how. I'm using a hosted solution on Wikia. So I am unable to modify the installation, add extensions or hack the settings. But I have admin rights on my wiki so I can access the MediaWiki namespace and MediaWiki:Common.js.
The javascript I want to use (Tangle) will consist of an external script that will be common to a number of pages(but not all pages in the wiki) and some code that will be specific to each page, the kind you would normally put inline in the <script> tag.
The trouble is, Mediawiki sanitizes <script> tags, and I haven't been able to find a way to put them in. I'm trying to make this into an editor-friendly setup that will be used across the wiki, so I'm also trying to avoid hacks and find a proper solution.
Update: New problem
Apparently MediaWiki also sanitizes the HTML5 data attributes, which Tangle relies on heavily. Any ideas on solving that problem is very welcome.
MediaWiki doesn't allow <script> tags in pages for obvious reasons: if it did, anyone could use them to inject JavaScript into your wiki and e.g. steal login credentials.
There are a couple of things you could do:
Write some generic JavaScript code to extract the parameters from something that is allowed on MediaWiki pages, such as a hidden <div>. Be careful not to introduce security holes when doing that.
Add something like this to MediaWiki:Common.js:
importScript('MediaWiki:Tangle/' + wgPageName + '.js');
Then, whenever a user visits the page "Foo", the page "MediaWiki:Tangle/Foo.js" will be loaded as JavaScript. Of course, that page will only be editable by admins, but that might still be enough for your needs. (You could use the same trick to import JS from pages in other namespaces, but that would open a security hole miles wide.)

Only running javascript required for current page, best methods?

So I know it's best to have one javascript file for an entire site to limit http requests. So obviously only some javascript is required for some pages. What is the best way of only running the javascript required for the current page?
EG.
if(page=='home'){
//run javascript require for the home page
}
Maybe this isn't an issue and if targeting elements are not found on the page javascript will just fail gracefully? I would just like to know the best practice for this javascript structure.
Encapsulate your logic in functions. Then just call the function(s) you need in each page, either via "onload" or an embedded function call in the page:
<script type="text/javascript">
yourFunctionForThisPage();
</script>
Edit: Just to clarify: my answer is assuming the (implied) constraint of a single .js file. As others have pointed out, although you save on HTTP requests, this is not necessarily a good idea: the browser still has to parse all the code in the file for each page, whether used or not. To be honest it's pretty unusual to have a global site-wide js resource with everything in it. It's probably a much better idea to logically split out your js into various files, i.e libraries. These libraries could be page-based - i.e specific code for a particular page, or algorithm/task-based that you can include in whatever pages need them.
Is this feasible?
While it is best to have just a single Javascript file per page to lower the number of requests yet it may not be feasible. Especially the way that you'd like to do it.
If you're asking how to join various scripts of various pages into a single script and then running just those parts that are related to a particular page then this is something you shouldn't do. What good is it for you to have one huge file with lots of scripts (also think of maintainability) compared to a few short integrated scripts? If you keep the number of scripts low (ie. below 10) you shouldn't be to worried.
The big downside is also that browser will load the complete script file which means it will take it more time to parse them as well as consume a lot more resources to use it. I'd strongly suggest against this technique of yours even though it may look interesting...
Other possibilities
The thing is that the number of Javascript files per page is low. Depending on the server side technology you're using there are tools that can combine multiple script files into one so every page will just request a single script file which will combine all those scripts that this particular page will use. There is a bit overhead on the server to accomplish this task, but there will be just one script request.
What do you gain?
every page only has scripts that it needs
individual script files are smaller hence easier to maintain
script size per request is small
browser parsing and resource consumption is kept low
Know what you will need on the page and use a script loader like labjs.
Also, remember that your specific case might be different from what others have found, so you might want to do some tests, to verify if, for example, having 5 little files, is better (or worse) than 1 big file.
The only way to be sure is to test different options yourself and come up with a fitting solution.

What is the "acceptable" upper limit for JavaScript array size?

I left this question as generic as possible, but I do have a specific problem that I need to solve in my application and the answer to this would help.
The application I am working on uses PHP/MySQL as its backend, and is set up so that no text/words/phrases visible to the user are hardcoded in the HTML/JS that is output to the browser, rather they are stored in a database table associated with a language key that is used to fetch the correct translation of the word/phrase based on the user's language preference. Now this works great for text that exists inside the application's HTML, but in order for this system to work with the javascript files, all javascript must be placed in a .php file and wrapped in <script></script> tags and included inline with the HTML, CSS ect.
This creates some problems with the flexibility in the system's javascript, as it cannot be included as external scripts via <link> tags (I guess unless you set the .php file's headers manually), and perhaps more importantly it cannot be minified/packed etc. when served in the production environment.
My first thought of a solution to this problem is to have a php script that's placed before any other javascript which loops through every record in the language database table and creates an associative javascript array using the language key as the array keys and setting their value to the translated phrase according to the user's preference. So, in this way all javascript files could be made into actual .js files and link'ed, minified, packed, etc. as needed, and they would just reference the phrases they need from the master language array that was created (i.e. alert(LANGUAGE.some_text);)
Only problem is, the number of elements in this array could easily get into the thousands possibly even bigger. So back to my original question, what is an acceptable max size for a javascript array, based on the average PC? Or am I attacking this problem entirely wrong to begin with?
I think the problem has less to do with how much data javascript can theoretically handle and more to do with how your application is handling the data.
It sounds like you're returning all of the phrases for the user's language on every page, not just the phrases they need on that particular page. If that's the case, fixing it will be part of the solution to your problem.
The rest of the solution will be not using javascript for anything until the app is completely functional. Then go back and do progressive enhancement stuff with js.
Instead of generating javascript from those database queries, generate pages (server-side) in the user's natural language, and serve them from a separate subdomains/subdirectories. Have your web server load the appropriate config for the user's language based on subdomain/subdirectory.
It's not the answer you were looking for, but I hope it helps.
JavaScript is by its nature a scripting language. The interpreter is nestled inside the browser's kernel. Correct me if I'm wrong, but I don't believe there is a definitive upper limit. The only thing that constricts an unlimited upper bound are memory constraints.
You can house gigs of uncompressed data (more if you compress it).
You're more likely to get one of the top errors in the list here, before you'll see any "upper bound limit reached."
in order for this system to work with the javascript files, all javascript must be placed in a .php file and wrapped in tags and included inline with the HTML, CSS ect.
This creates some problems with the flexibility in the system's javascript, as it cannot be included as external scripts via tags
Actually, not necessarily true. You can serve javascript files (not html) using PHP. Of course doing this most likely mean that all your javascript file will have the extension .php but that is a small matter. If you don't care about being strictly correct you don't even have to set the Content-type to js since browsers will treat anything served by <script> tags as javascript anyway.
A lot of sites actually do this, though not necessarily in PHP. Google, Yahoo etc often serve javascript using a server side scripting language to enable them to do any or all of the following:
automatically concatenate javascript/css files into a single file
automatically minify the javascript/css files
automatically obfuscate the javascript files
automatically do dependency resolution to source needed javascript files
Some people use mod_rewrite to rename the .php (or .pl or .cgi) files to .js to hide the details of the implementation. But it's strictly not necessary.
Here's an example bookmarklet that I serve as a .php file.
I tried solving a similar problem as a non-web programmer before, and ended up hosting the language package as a separate XML which JS queries into. Bad idea, and I'll tell you why. Google can't see pages filled dynamically with JS. But if that's no issue to you, I would recommend that way, simply because I don't know any other. :)
The method Array.prototype.push , append arguments to the end of the array, and return the new length.
In some JavaScript engine such as v8, the length is bounded to 32bit unsigned integer, so this might be the limit you want to know.

Categories

Resources