Polymer: Registering Elements in External Scripts - polymer

In most of the examples I've seen for creating elements the script that registers the element is defined in the component's HTML file, e.g.
<link rel="import" href="/components/polymer/polymer.html">
<polymer-element name="my-element">
<template>
...
</template>
<script>
// convenience wrapper for document.registerElement
Polymer('my-element', {
...
});
</script>
</polymer-element>
It's possible to do that registration in an external script instead, e.g.
<script src="my-element.js"></script>
That seems like an attractive option because the script then becomes visible to tools like JSHint, but then you lose the automatically generated documentation of attributes, etc.
Is there a workflow or set of tools that help you get the best of both worlds?
e.g. combine a raw template and script into a single HTML file in a similar way to preprocessing CSS with Sass?

Yes. Polymer supports registering an element with by referencing an external script. See http://www.polymer-project.org/docs/polymer/polymer.html#separatescript. An original reason the element is in the call to Polymer() is to support this. It associates the definition with the script.

Related

Vuejs 2: How to include (and run) a script tag javascript file in the DOM dynamically?

I am using Vuejs and I need to insert script tags in the DOM dynaically to embed JWPlayer videos in this way:
<body>
<!-- HTML content -->
<script src="//content.jwplatform.com/players/KZVKrkFS-RcvCLj33.js"></script>
<!-- More HTML content -->
<script src="//content.jwplatform.com/players/ANOTHER-ID-ANOTHER-PLAYERID.js"></script>
</body>
I have used without results: v-html directive to render the html tags. As well v-bind:src but neither execute the code. I found this solution but it did not work either: How to add external JS scripts to VueJS Components
I used this solution but the script tags (one for each video) must be inserted in the body (not in head): they should create div tags containers and embed the videos. The problem is that the embeded JWPlayer file contains a document.write() statement. And the browser console says: "A call to document.write() from an asynchronously-loaded external script was ignored."
Is there anyway to achieve this?
The link you provided should work.
You probably just need to wait for the script to load before you can use JWPlayer.
const script = document.createElement('script')
script.onload = () => {
// Now you can use JWPlayer in here
}
script.src = '//content.jwplatform.com/players/MEDIAID-PLAYERID.js'
document.head.appendChild(script)
Also make sure you only do this one time for the first component that requires it, from that point onward JWPlayer will be loaded and you can use it without inserting another script tag.

Proper order for scripts in head of my document [duplicate]

When embedding JavaScript in an HTML document, where is the proper place to put the <script> tags and included JavaScript? I seem to recall that you are not supposed to place these in the <head> section, but placing at the beginning of the <body> section is bad, too, since the JavaScript will have to be parsed before the page is rendered completely (or something like that). This seems to leave the end of the <body> section as a logical place for <script> tags.
So, where is the right place to put the <script> tags?
(This question references this question, in which it was suggested that JavaScript function calls should be moved from <a> tags to <script> tags. I'm specifically using jQuery, but more general answers are also appropriate.)
Here's what happens when a browser loads a website with a <script> tag on it:
Fetch the HTML page (e.g. index.html)
Begin parsing the HTML
The parser encounters a <script> tag referencing an external script file.
The browser requests the script file. Meanwhile, the parser blocks and stops parsing the other HTML on your page.
After some time the script is downloaded and subsequently executed.
The parser continues parsing the rest of the HTML document.
Step #4 causes a bad user experience. Your website basically stops loading until you've downloaded all scripts. If there's one thing that users hate it's waiting for a website to load.
Why does this even happen?
Any script can insert its own HTML via document.write() or other DOM manipulations. This implies that the parser has to wait until the script has been downloaded and executed before it can safely parse the rest of the document. After all, the script could have inserted its own HTML in the document.
However, most JavaScript developers no longer manipulate the DOM while the document is loading. Instead, they wait until the document has been loaded before modifying it. For example:
<!-- index.html -->
<html>
<head>
<title>My Page</title>
<script src="my-script.js"></script>
</head>
<body>
<div id="user-greeting">Welcome back, user</div>
</body>
</html>
JavaScript:
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.getElementById("user-greeting").textContent = "Welcome back, Bart";
});
Because your browser does not know my-script.js isn't going to modify the document until it has been downloaded and executed, the parser stops parsing.
Antiquated recommendation
The old approach to solving this problem was to put <script> tags at the bottom of your <body>, because this ensures the parser isn't blocked until the very end.
This approach has its own problem: the browser cannot start downloading the scripts until the entire document is parsed. For larger websites with large scripts and stylesheets, being able to download the script as soon as possible is very important for performance. If your website doesn't load within 2 seconds, people will go to another website.
In an optimal solution, the browser would start downloading your scripts as soon as possible, while at the same time parsing the rest of your document.
The modern approach
Today, browsers support the async and defer attributes on scripts. These attributes tell the browser it's safe to continue parsing while the scripts are being downloaded.
async
<script src="path/to/script1.js" async></script>
<script src="path/to/script2.js" async></script>
Scripts with the async attribute are executed asynchronously. This means the script is executed as soon as it's downloaded, without blocking the browser in the meantime.
This implies that it's possible that script 2 is downloaded and executed before script 1.
According to http://caniuse.com/#feat=script-async, 97.78% of all browsers support this.
defer
<script src="path/to/script1.js" defer></script>
<script src="path/to/script2.js" defer></script>
Scripts with the defer attribute are executed in order (i.e. first script 1, then script 2). This also does not block the browser.
Unlike async scripts, defer scripts are only executed after the entire document has been loaded.
(To learn more and see some really helpful visual representations of the differences between async, defer and normal scripts check the first two links at the references section of this answer)
Conclusion
The current state-of-the-art is to put scripts in the <head> tag and use the async or defer attributes. This allows your scripts to be downloaded ASAP without blocking your browser.
The good thing is that your website should still load correctly on the 2% of browsers that do not support these attributes while speeding up the other 98%.
References
async vs defer attributes
Efficiently load JavaScript with defer and async
Remove Render-Blocking JavaScript
Async, Defer, Modules: A Visual Cheatsheet
Just before the closing body tag, as stated on Put Scripts at the Bottom:
Put Scripts at the Bottom
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
Non-blocking script tags can be placed just about anywhere:
<script src="script.js" async></script>
<script src="script.js" defer></script>
<script src="script.js" async defer></script>
async script will be executed asynchronously as soon as it is available
defer script is executed when the document has finished parsing
async defer script falls back to the defer behavior if async is not supported
Such scripts will be executed asynchronously/after document ready, which means you cannot do this:
<script src="jquery.js" async></script>
<script>jQuery(something);</script>
<!--
* might throw "jQuery is not defined" error
* defer will not work either
-->
Or this:
<script src="document.write(something).js" async></script>
<!--
* might issue "cannot write into document from an asynchronous script" warning
* defer will not work either
-->
Or this:
<script src="jquery.js" async></script>
<script src="jQuery(something).js" async></script>
<!--
* might throw "jQuery is not defined" error (no guarantee which script runs first)
* defer will work in sane browsers
-->
Or this:
<script src="document.getElementById(header).js" async></script>
<div id="header"></div>
<!--
* might not locate #header (script could fire before parser looks at the next line)
* defer will work in sane browsers
-->
Having said that, asynchronous scripts offer these advantages:
Parallel download of resources:
Browser can download stylesheets, images and other scripts in parallel without waiting for a script to download and execute.
Source order independence:
You can place the scripts inside head or body without worrying about blocking (useful if you are using a CMS). Execution order still matters though.
It is possible to circumvent the execution order issues by using external scripts that support callbacks. Many third party JavaScript APIs now support non-blocking execution. Here is an example of loading the Google Maps API asynchronously.
The standard advice, promoted by the Yahoo! Exceptional Performance team, is to put the <script> tags at the end of the document's <body> element so they don't block rendering of the page.
But there are some newer approaches that offer better performance, as described in this other answer of mine about the load time of the Google Analytics JavaScript file:
There are some great slides by Steve Souders (client-side performance expert) about:
Different techniques to load external JavaScript files in parallel
their effect on loading time and page rendering
what kind of "in progress" indicators the browser displays (e.g. 'loading' in the status bar, hourglass mouse cursor).
The modern approach is using ES6 'module' type scripts.
<script type="module" src="..."></script>
By default, modules are loaded asynchronously and deferred. i.e. you can place them anywhere and they will load in parallel and execute when the page finishes loading.
Further reading:
The differences between a script and a module
The execution of a module being deferred compared to a script(Modules are deferred by default)
Browser Support for ES6 Modules
If you are using jQuery then put the JavaScript code wherever you find it best and use $(document).ready() to ensure that things are loaded properly before executing any functions.
On a side note: I like all my script tags in the <head> section as that seems to be the cleanest place.
<script src="myjs.js"></script>
</body>
The script tag should always be used before the body close or at the bottom in HTML file.
The Page will load with HTML and CSS and later JavaScript will load.
Check this if required:
http://stevesouders.com/hpws/rule-js-bottom.php
The best place to put <script> tag is before closing </body> tag, so the downloading and executing it doesn't block the browser to parse the HTML in document,
Also loading the JavaScript files externally has its own advantages like it will be cached by browsers and can speed up page load times, it separates the HTML and JavaScript code and help to manage the code base better.
But modern browsers also support some other optimal ways, like async and defer to load external JavaScript files.
Async and Defer
Normally HTML page execution starts line by line. When an external JavaScript <script> element is encountered, HTML parsing is stopped until a JavaScript is download and ready for execution. This normal page execution can be changed using the defer and async attribute.
Defer
When a defer attribute is used, JavaScript is downloaded parallelly with HTML parsing, but it will be execute only after full HTML parsing is done.
<script src="/local-js-path/myScript.js" defer></script>
Async
When the async attribute is used, JavaScript is downloaded as soon as the script is encountered and after the download, it will be executed asynchronously (parallelly) along with HTML parsing.
<script src="/local-js-path/myScript.js" async></script>
When to use which attributes
If your script is independent of other scripts and is modular, use async.
If you are loading script1 and script2 with async, both will run
parallelly along with HTML parsing, as soon as they are downloaded
and available.
If your script depends on another script then use defer for both:
When script1 and script2 are loaded in that order with defer, then script1 is guaranteed to execute first,
Then script2 will execute after script1 is fully executed.
Must do this if script2 depends on script1.
If your script is small enough and is depended by another script
of type async then use your script with no attributes and place it above all the async scripts.
Reference: External JavaScript JS File – Advantages, Disadvantages, Syntax, Attributes
It turns out it can be everywhere.
You can defer the execution with something like jQuery so it doesn't matter where it's placed (except for a small performance hit during parsing).
The most conservative (and widely accepted) answer is "at the bottom just before the ending tag", because then the entire DOM will have been loaded before anything can start executing.
There are dissenters, for various reasons, starting with the available practice to intentionally begin execution with a page onload event.
It depends. If you are loading a script that's necessary to style your page / using actions in your page (like click of a button) then you better place it at the top. If your styling is 100% CSS and you have all fallback options for the button actions then you can place it at the bottom.
Or the best thing (if that's not a concern) is you can make a modal loading box, place your JavaScript code at the bottom of your page and make it disappear when the last line of your script gets loaded. This way you can avoid users using actions in your page before the scripts are loaded. And also avoid the improper styling.
Including scripts at the end is mainly used where the content/ styles of the web page is to be shown first.
Including the scripts in the head loads the scripts early and can be used before the loading of the whole web page.
If the scripts are entered at last the validation will happen only after the loading of the entire styles and design which is not appreciated for fast responsive websites.
You can add JavaScript code in an HTML document by employing the dedicated HTML tag <script> that wraps around JavaScript code.
The <script> tag can be placed in the <head> section of your HTML, in the <body> section, or after the </body> close tag, depending on when you want the JavaScript to load.
Generally, JavaScript code can go inside of the document <head> section in order to keep them contained and out of the main content of your HTML document.
However, if your script needs to run at a certain point within a page’s layout — like when using document.write to generate content — you should put it at the point where it should be called, usually within the <body> section.
Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.
There are some different techniques, but the most straightforward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.
This naturally requires that the script itself is not needed for the rendering of the page.
For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow, but now at Google).
Script blocks DOM load until it's loaded and executed.
If you place scripts at the end of <body>, all of the DOM has a chance to load and render (the page will "display" faster). <script> will have access to all of those DOM elements.
On the other hand, placing it after the <body> start or above will execute the script (where there still aren't any DOM elements).
You are including jQuery which means you can place it wherever you wish and use .ready().
You can place most of <script> references at the end of <body>.
But if there are active components on your page which are using external scripts, then their dependency (.js files) should come before that (ideally in the head tag).
The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute the JavaScript code.
<script> ... your code here ... </script>
</body>
And if you write in jQuery, the following can be in the head document and it will execute after the document loads:
<script>
$(document).ready(function(){
// Your code here...
});
</script>
If you still care a lot about support and performance in Internet Explorer before version 10, it's best to always make your script tags the last tags of your HTML body. That way, you're certain that the rest of the DOM has been loaded and you won't block and rendering.
If you don't care too much any more about in Internet Explorer before version 10, you might want to put your scripts in the head of your document and use defer to ensure they only run after your DOM has been loaded (<script type="text/javascript" src="path/to/script1.js" defer></script>). If you still want your code to work in Internet Explorer before version 10, don't forget to wrap your code in a window.onload even, though!
I think it depends on the webpage execution.
If the page that you want to display can not displayed properly without loading JavaScript first then you should include the JavaScript file first.
But if you can display/render a webpage without initially download JavaScript file, then you should put JavaScript code at the bottom of the page. Because it will emulate a speedy page load, and from a user's point of view, it would seems like that the page is loading faster.
Always, we have to put scripts before the closing body tag expect some specific scenario.
For Example :
`<html> <body> <script> document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script> </body> </html>`
Prefer to put it before the </body> closing tag.
Why?
As per the official doc: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/JavaScript_basics#a_hello_world!_example
Note: The reason the instructions (above) place the element
near the bottom of the HTML file is that the browser reads code in the
order it appears in the file.
If the JavaScript loads first and it is supposed to affect the HTML
that hasn't loaded yet, there could be problems. Placing JavaScript
near the bottom of an HTML page is one way to accommodate this
dependency. To learn more about alternative approaches, see Script
loading strategies.

Polymer 2.x : How do I scope Foreign stylesheets and / or Are #imports shimmed

There have been questions doing the rounds , making a lot of people try stubbornly force scoping an external css into a Polymer element..
by hook or crook
And then the heart break of an #import not working, or a link rel=stylsheet not scoped
So,
How do I as an author / consumer of a polymer element, scope foreign stylesheets?
What are some gotchas? is #import supported and shimmed?
Can I Scope external CSS Stylesheets to within a Polymer Custom Element
TL;DR :
use link rel=import and pass the url of your external stylesheet to the poly-style tool
Note Polymer still can not shim an #import , or stuff with external urls , that require a fetch before the shim
Also, <link rel=stylesheet... is not scoped , but can be used.It is also, not shimmed into your element.
Polymer up until 1.0 defined the use of <link> tags with attributes
rel = import
type = css
and whatever href as long as it obeyed CORS principles
Everything was all fancy and we all held hands and sang kumbaya
With Polymer 2.0 and actually even the later versions of polymer 1.0,
something called style-modules were introduced where, you encapsulate
all your handwritten styles inside of a template in a dom-module container
<dom-module id="my-style">
<template>
<style>
.class_1{
/*all class_1 styles*/
}
.class_2{
/*all class_1 styles*/
}
.class_3{
/*all class_1 styles*/
}
</style>
</template>
</dom-module>
And then you'd essentially import these handwritten styles into your custom element
<link rel=import href=my-style.html />
<dom-module id="my-app">
<template>
<style include=my-style>
</style>
</template>
</dom-module>
Oh Snap! Now, I'd have to copy over entire stylesheets first, then wrap them in a <dom-module>
and then import them over to my app! we retorted.
And then there were numerous queries about deduplication and all those sort of anxieties
So, the preferred or suggested solution rather, was to read and search through stylesheets and copy over only those classes deemed necessary.
Polymer Also has yet to rid itself with the deprecated
<link rel=import type=css... />
css shimmer .
basically, even with polymer 2.0, you can use the above, albeit, you now need to actually place it inside of your <dom-module>.
and polymer shims it.
Some gotchas :
you simply can not have the dreadful #import rules inside those stylesheets
#imports require polymer to fetch the resource async and hence can not guarantee a shim - hence no support.
Now on some browsers, you might see this lingering in the shadows of your dev console:
Resource interpreted as Document but transferred with MIME type text/css: "https://a.b.com/additional.css".
This doesn't necessarily mean the resource wasn't fetched, but hey if your web server has a no-sniff
or any content integrity header set, that'd mean, the browser can not interpret a css as an html.
now since <link rel=import... is meant for HTML Imports , that'd mean, the browser has to accept only html as a response content type.
Hence, style modules are the best way to go while importing and scoping css to your components.
How then would I import an external stylesheet.. say a font-awesome ?
well, polymer has the web tool residing at
this web based style module builder for polymer
Now this web tool , duly gives you the required content-type and access-control headers.
Since the response is text/html , no more warnings on the console either.
So, How do I build my style module?
simple, use link rel=import and pass the url of your external stylesheet to the poly-style tool
<link rel="import" href="https://poly-style.appspot.com?id=poly-fa-style-module&url=https://use.fontawesome.com/releases/v4.7.0/css/font-awesome-css.min.css">
<dom-module id="poly-fa">
<template id="poly-fa-styler" strip-whitespace>
Now, all you need to do is, do an <style include=poly-fa> within your apps. and you have a scoped font awesome.
Caution!
This will still not support #imports
Also, ::slotted DOM, can not be styled by style-modules via shared styles, except under some scenarios where, you import the stylesheet into a higher element in the hierarchy
Gulp
The above tool is ideal for authors, who may choose not to prefill required external styles for their components in their custom elements, and fetch external css when necessary
for people who might want to pre fill external styles into their components, I have heard of a gulp plugin here , although I am yet to use it.

How to use x3dom with polymer?

I have a polymer site where I'd like to use the x3dom library to view an external x3d file, and simply be able to rotate the loaded 3D scene 360 degrees.
Has anyone successfully used x3dom with polymer? I don't see any reason why this wouldn't work. Please assume I have all the polymer stuff correct (which I have) and have loaded the prerequisite x3dom.js script and x3dom.css in the head of the page too. This is just a stripped down code snippet to show key bits:
<x3d width='350px' height='400px'>
<scene>
<inline nameSpaceName="myNS" mapDEFToID="true" url="{{_x3dPath}}"></inline>
</scene>
</x3d>
<script>
Polymer({
properties: {
_x3dPath: {type: String},
},
ready: function() {
this._x3dPath = "/someDynamicPath/threeDfile.x3d";
}
});
</script>
Any suggestions?
You need to create a custom element that serves as a wrapper for the 3rd party library. (e.g x3dom-wrapper.html ).
Inside that file, you must add the script reference to x3dom .js
<script type="text/javascript" src='../bower_components/x3dom/x3dom.js'></script>
Then, you need to import the wrapper custom element like any other polymer component. That way you ensure the x3dom dependency will be available when you need it.
Edit:
Wrapping the library is still a good practice but not the cause of your problem. I did a quick test and found that you must call x3dom.reload() on your "ready" polymer event handler. That way x3dom system reloads properly

Working with Polymer and requirejs

In an attempt to create polymer elements that use requirejs modules I ran into a blocking issue. I understand that polymer is not designed to work with requirejs, but for the time being It is my only option.
Searching for answers I found two solutions:
Don't use requirejs and make your modules compatible with HTML imports.
Put Polymer() call inside the requirejs callback as described here
Since I have to use require, at least for the time being, I went with the solution no.2. However, it turns out the solution causes asynchronous delays of element registration and incorrect data binding prior to Polymer upgrading the element.
Digging deeper into this issue, I started hacking undocumented Polymer internals with an intention to stop Polymer entirely until requirejs does its thing. Here is what I came up with:
Polymer.require = function(tag, deps, func) {
var stopper = {}
Polymer.queue.wait(stopper);
require(deps, function() {
delete stopper.__queue;
Polymer.queue.check();
Polymer(tag, func.apply(this, arguments));
});
};
I know this is terribly wrong. Is there a better solution?
I found that if I embed the call to require within the Polymer script I avoid this issue.
<link rel="import" href="../polymer/polymer.html"/>
<script src="../requirejs/require.js"></script>
<script src="../something/something.js"></script>
<polymer-element name="some-component">
<template>...</template>
<script>
(function() {
Polymer('some-component', {
someMethod: function () {
require(['something'], function (Something) {
var something = new Something();
...
}
}
)();
</script>
</polymer-element>
So there's this solution from Scott Miles but I find it a bit simplistic and inflexible as it relies on:
<script> tags to be executed in order, therefore ruling out:
async script tags
xhr based script loading
polymer getting loaded from a <script> tag, therefore:
layout.html and associated css won't be loaded
any future call to polymer.html won't be deduped
If you want more control over your bootstrapping logic you will need to enforce some amount of synchronisation between your components (which is what both requirejs and polymer are competing to do) before those are fully loaded.
The previous example is a more declarative (read polymer) way of doing things but falls short of fine grained tuning. I've started working on a repository to show how you can fully customise your load ordering, by using a more imperative approach where requirejs is given priority to orchestrate the rest of the bootstrapping.
At the time of writing, this extra control comes at the price of worse performance as the various scripts can't be loaded in parallel but I'm still working on optimising this.