Polymer and working with external JavaScript Libraries - javascript

With Shadow DOM, I can easily use external CSS frameworks like bootstrap nicely and it will only apply to my scope which is nice (example here).
However, this doesn't apply to JavaScript libraries as far as I know. If I, for example, need to work with jQuery on my web component, I basically make it available for entire page. What is the recommend way to work with external JavaScript libraries with Polymer? How should I handle cases where my web component (which is distributed through bower) needs one version of foo.js and the consumer needs another?

There is no JavaScript encapsulation solutions I know of.
Check if js encapsulation solutions exist, e.g. check zonejs and alternatives.
You may do it yourself but this will require you to devote some time to it. E.g. I've encapsulated Babel with with statement as shown here (not tested).

Related

Wrapping JavaScript libraries to allow multiple versions without conflicts

Background
We currently use jQuery to dynamically add third-party JavaScript libraries to our main index.html file at runtime (this is extremely simplified, but should help in understanding). Once they're added, the browser handles downloading them.
I'm wondering if there is there a way via some JavaScript library (or homegrown way) to dynamically modularize or wrap the third-party JavaScript libraries so that two versions of the same library can be loaded without conflicts and can be referenced independently?
For example:
Version A of 'underscore.js' could be referenced as:
versionA._.noop()
Version B of 'underscore.js' could be referenced as:
versionB._.noop()
Thus allowing both versions of 'underscore.js' to be available, but not conflict with each other?

Creating and reusing custom elements with jQuery vs Polymer vs Dust.js

I've written some widgets to use in my web app, and I'd like to be able to plug these widgets in throughout the app without pasting big chunks of widget code. So far I've been writing custom HTML tags and using jQuery selectors and CSS to populate and style my tags. The end result allows me to write <myTag></myTag> anywhere on a page, and have my custom widget appear.
Recently, I've learned about Dust JS and Google's Polymer Project. My understanding is that Dust would allow me to write a template and "swap out" parts of the template with my content, while Polymer would allow me to create custom HTML tags as I've been trying to do and place them wherever I'd like.
Would it benefit me to use Dust or Polymer? What is the difference between those two options and simply using jQuery to select my tags and plug in my widget/styles? Obviously these are three drastically different libraries/frameworks, but it seems to me that there is some overlap when it comes to my use case. Please correct me if I'm wrong.
Edit: Say I have a plain old HTML page. The question I'm getting at is what would prevent me from using {myCustomWidget} in Dust to "plug in" my widget throughout the app, other than the fact that this may not be standard usage? Similarly, why would I use Polymer to create "shortcuts" for my widgets over using a jQuery selector?
Thanks!
I don't know a ton about Dust, but I've made fairly heavy use of both jQuery and Polymer. Someone with more Dust experience should totally weigh in. It looks like one of the main advantages of Dust is that it's designed for efficient server-side rendering. It's also format agnostic whereas jQuery and Polymer are both specialized for HTML.
Polymer is designed for the use case of creating encapsulated widgets that can be easily reused. It's got a few advantages over rolling your own system with jQuery:
A Polymer element can be imported with one line, and the import will pull in its html, js, and css, and it will register the element within the page.
Polymer has support for data binding, meaning that you typically don't have to write code to ensure that the widget is updated after some data changes. When the data changes, all of the widgets that are interacting with that respond immediately and automatically.
Polymer interops really well with jQuery, so if you've got a site that's doing a lot of jQuery style interaction today you can gradually introduce Polymer elements and they'll play well with the rest of your page. e.g.
$('<my-slider>').appendTo('body') // append the slider widget to the page
$('my-slider').attr('value') // get the current value of the slider
$('my-slider').attr('value', 100) // set the value of all sliders
etc
The styling of a polymer element is encapsulated, meaning that a widget will not mess up the rest of the page with its CSS, and the enclosing page won't mess up the styling of the widget (though the enclosing page can style the widget it has to be fairly intentional, just setting something like * { padding: 5px; } won't throw everything off).
There's great docs at http://www.polymer-project.org/ (and after getting started, I strongly recommend the API docs, they're quite complete and informative: http://www.polymer-project.org/docs/polymer/polymer.html )
I've not used Polymer before but I've used Dust and jQuery extensively.
Dust is simply a template library, just like Handlebars,Mustache, Twig and the myriad of other template libraries out there. It's written in javascript and can be used with NodeJS or can easily run in the browser if you're building client side applications.
Both Dust and jQuery can be used together. Dust would render your HTML templates and as always, jQuery would be used to manipulate them and do whatever else you normally do with jQuery such as listen to events and handle them accordingly.
It's important to note that the two aren't alternatives but rather they work together. Dust cannot do the things that jQuery does and is not meant to. Dust works very well when you have large templates that require partials and blocks.
At its core, Polymer is a platform of polyfills for the current implementation of the WC3 web component recommendation as well as some aspects of ECMA 6 such as Object.observe() and WeakMap. Included in the Platform are the libraries NodeBind and TemplateBinding which enable observable (two-way) custom element data-binding.
Dustjs is an asynchronous logic-less templating engine for client-side and server-side(Nodejs)
rendering. There is no native concept of an observable in Dustjs(as is the case for most template engines), meaning two-way data-binding is outside the scope of the project. However, the PayPal roadmap for Dustjs indicates two-way data-binding may receive official support by the end of 2014.
That being said, NodeBind and observe-js are separate repos not necessarily tied to the Polymer custom element implementation, meaning you can use them in your own projects--which is exactly what I did.
My biggest criticism of client-side rendering frameworks like Polymer (and in some respects, angularjs), is that they are not SEO compatible. So I actually combined NodeBind with Dustjs to make my own two-way data-bound custom element implementation derived from the Polymer platform. The idea is that Dustjs renders the template server-side(or even client-side, if SPA) and then upon rendering, you bind the Dust context to an observable and then parse the template fragment for attributes and keys, binding them to a path observer which maps to the observable. So, the bulk of the task is to write your own parser. The good news is that you can use the Dust parser to help your code. The bad news is that if you want to support arbitrary depths, it is far from a simple task(involves quite a bit of recursion). The other non-trivial task is to support path observer rebinding in the event of model list additions and subtractions.
A final note: Dustjs inheritance offers a superior way to reference your custom elements without relying on HTML Imports and ajax like Polymer.
You can do something like this:
{>my-element}
simply as a partial. And in my-element.html
<my-element>
<ui-template id="my-element-frag">...</ui-template>
</my-element>
this does require a second-step in your build process(grunt or gulp) that requires you to not only compile the external files but to parse your external files for your "template tags" and compile those as separate templates, which can then be referenced by, say, the id attribute(as the template name).

Packaging client-side scripts at runtime with support for Common.js

I am writing a web server in Node.js, and I want it (among other things) to deliver a single JavaScript file to the client which contains my client SDK. The SDK is basically an object which provides lots of functionality the client can use.
I need to build the SDK from various sources:
3rd party libs, such as AngularJS
Custom code, which is stored in static .js files on the server
Custom code, which is created dynamically in-memory at runtime
For being able to test my custom code (#2) easily, and for being able to share this code with the server-side as well, it would be great if I could write it according to CommonJS.
I do not have too much experience with bundling things up for the client-side, but I know UglifyJS and Browserify.
If it was only about concatenating some files (and perhaps minifying them), I knew what to do with UglifyJS. If it was only about delivering some stuff that is compatible to CommonJS, I also knew what to do with Browserify. What I don't get is their combination, and this in addition with demand #3 - the dynamically generated code.
This essentially means that I am not able to use Grunt for this, but that everything needs to be done at runtime (please let's not discuss why I want to do it like this).
So … I'm somewhat lost. Can anybody help clarify things for me? How do I have to put all these pieces together so that I finally end up with a single deliverable that can be sent to the client, and that the client can use?
Basically, what the client should end up with is a number of global objects such as $, angular and my very own custom object, but all this by only loading one single file.
How could I do this?
PS: I do not have the need to put the result to disk on the server, if it's a pure in-memory solution that's perfectly fine for me (and is even preferred, as then I do not need write access to the file system).
Imho webpack provides all the features you need. It's a bundler like browserify but I find it more flexible and extensible. webpack is agnostic to different module styles (CommonJS, AMD, ES6 or old-school globals) and is able to apply and chain pre-processors on modules. These are called loaders (according to the CommonJS spec) and can be used to generate code dynamically. Usually they transform LESS to CSS or CSS to JavaScript, but they can be used for any dynamic task.
To provide your global $, angular and your custom object you could use the script-loader, which runs the given module classically in a global context.
What you're looking for is called "asset pipeline".
You can use mincer (I didn't try it, but it looks very promising) or asset-pipeline (certainly will do the job, but is kinda deprecated).

Calling javascript

I am setting up a site that relies on a lot of javascript items and i want to try and set it up so the pages only call what they need.
there are different types of functionality so i am goig to break them into their own js files to make it easy to use.
For example if there is a drag and drop functionality then i will include the js file for drag and drop. within that will be a generic call using a class to turn on the functionality. This way it is only used on a page that uses drag and drop.
This gets more compacted when i have ajax calls some are on change events on a select for example while others are on a button.
I could separate these into different files for each type perhaps.
my concern is if a call needs more parameters to be passed or a different url then where does this code go to make the call?
I don't really want to have code within the page itself if i can help it.
I would love to hear your thoughts on how to best set this up
RequireJS might be your answer:
RequireJS is a JavaScript file and module loader. It is optimized for
in-browser use, but it can be used in other JavaScript environments,
like Rhino and Node. Using a modular script loader like RequireJS will
improve the speed and quality of your code.
This sounds similar to what I'm doing, so here what I've done:
One central file that contains functions that are used pretty much everywhere.
A folder containing files that are used in several places, but aren't worth including everywhere.
A folder containing files that are only used on one page.
Then, simply include the necessary <script> tags and go!
Hmm, have you looked at existing frameworks http://speckyboy.com/2010/05/17/15-javascript-web-ui-libraries-frameworks-and-libraries/?

Is there a lightweight library to do draggable+sortable lists inside greasemonkey scripts?

I'm writing a GreaseMonkey script, as part of which I'd like to sort a list by dragging its items. I'm using mootools, but the component for sortable lists doesn't work in the GM sandboxed environment. Can you recommend a smallish library/piece of code to do list sorting in the most lightweight fashion? I want it to be independant of any large framework and don't feel like implementing it myself.
If you need to debug a library such as mootools, instead of #require-ing it, just copy/paste the entire source into your own script. Then you can debug it the same as your own code.
On another note, this script includes the ability to drag-and-drop it's own window around the screen, with no additional library. Maybe you could analyze it and borrow code?
Use this Javascript QuickSort implementation
I'm not sure if there are any particular issues with just MooTools, but in general you may include external scripts into a GreaseMonkey script.
This has been addressed in previous questions like this one or this, as well as on the GreaseSpot wiki.

Categories