Is there any point in a JS file that has no functions? - javascript

I've got Olapic's API in front of me, and it looks something like this:
<script src="https://olapic_source.net"
data-olapic="olapic_specific_widget"
data-instance="213598612346580671235"
data-apikey="081274081760283650812734612"
data-tags="product_ID"
async="async">
</script>
I'm all for keeping JS out of HTML files wherever possible. I'm just wondering if there is any reason to put this in its own file, versus putting it right on the page.
The only requirement is that the script is located inside of a div class called "olapic_specific_widget"
So essentially
<div class="olapic_specific_widget">
<script src="path/to/external/file.js" type="text/javascript">
</script>
</div>
Which is tidier than
<div class="olapic_specific_widget">
<script src="https://olapic_source.net"
data-olapic="olapic_specific_widget"
data-instance="213598612346580671235"
data-apikey="081274081760283650812734612"
data-tags="product_ID"
async="async">
</script>
</div>
And so again, is there a point to this, or should I just leave all that stuff in there? If there is a point to it, I know you're supposed to take the script tag out of the external file. So, does my external file then look like this?
src="https://olapic_source.net"
data-olapic="olapic_specific_widget"
data-instance="213598612346580671235"
data-apikey="081274081760283650812734612"
data-tags="product_ID"
async="async"
Thanks for your time!

The script loaded from the src URL probably examines the page and looks for a <script> tag inside of a <div class="olapic_specific_widget">.
You cannot move any of the data- attributes out of the <script> tag, because the script loaded from src expects the <script> DOM element to contain those data- attributes. These settings are HTML attributes, not JavaScript.
In short, this <script> tag acts in two different roles at one:
a mechanism to import a remote script (because it has a src attribute)
a collection of widget settings, specified by data- attributes.
The remote script (that is imported by the <script> in role #1) reads the data that is set in the <script>'s attributes (in role #2).

You may consider this way to use the <script> element as a kind of remote function call. The several data attributes are the parameters of the call, and the script itself, as specified with the src URL, can perform a variety of actions depending on these parameters. This adds more flexibility in the design of JavaScript libraries for use in web pages.

Related

Include html in another html file for Adsence

I'm trying to include my Adsense code from a file called sda.html located in the home folder of the server.
I'm using this code to include it:
<div w3-include-html="../../sda.html" class="section_title text-center"></div>
from this source: https://www.w3schools.com/howto/howto_html_include.asp
but idk I feel there's something wrong.
btw my site is only HTML and js, so if there is any other better option I'll be glad to hear it.
I also checked this one down:
<!--#include virtual="/menu.shtml" -->
but I didn't use it, since I have no clue how my next server will operated. so I skip it.
and this one here:
<object data="../../sda.html"></object>
I prefer this one, but I have no control of the look of it, I couldn't center or anything
the smaller the code the better it is.
Does sda.html contains only adsense code or whole part of the page?
The includeHTML function from w3school is not very good. I suspect the issue you are having is that that function uses innerHTML to set content and innerHTML doesn't execute <script> tags with content: check "Security considerations" on MDN page.
To workaround this you can do the following: remove <script> tags from sda.html and then, once you imported HTML run window.adsbygoogle.push({}) for each new ad unit. Example:
Add adsbygoogle.js tag in of your page:
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
Insert ad into a div with id div-with-ad.
const divWithAd = document.querySelector('#div-with-ad');
divWithAd.innerHTML = `
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-0123456789101112"
data-ad-slot="9876543210"></ins>
`;
adsbygoog.push({});

Extract all classes from body element of AJAX-ed page and replace current page's body classes

I am in the process of AJAX-ing a WordPress theme with a persistent music player. Wordpress uses dynamic classes on the <body> tag. The basic structure is as follows:
<html>
<head>
</head>
<body class="unique-class-1 unique-class-2 unique-class-3">
<div id="site-container">
<nav class="nav-primary">
Other Page 01
Other Page 02
</nav>
<div class="site-inner">
<p>Site Content Here</p>
</div>
</div>
<div id="music-player"></div>
</body>
</html>
I am currently successfully loading the content of /other-page-01/, /other-page-02/, etc, using load('/other-page-01/ #site-container'). However, I need to extract all <body> classes from the AJAX loaded page and replace the current page's <body> classes with them dynamically.
Note: Replacing the entire <body> element is not an option due to the persistent <div id="music-player">. I've tried jQuery.get(), but couldn't get it to work.
How do I extract the <body> classes from the AJAX requested page and replace the current page's <body> classes with them?
I am not very familiar with jQuery or Javascript, so the exact code would be extremely helpful. Any help is greatly appreciated.
Thanks,
Aaron
My typical solution would have been to tell you to throw the AJAX code in to a jQuery object and then read it out like normal:
$(ajaxResult).attr('class');
Interestingly though, it appears you can't do this with a <body> element.
I'd say the easiest solution (if you have control over the resulting HTML) is to just use some good ol' regex:
var matches = ajaxResult.match(/<body.*class=["']([^"']*)["'].*>/),
classes = matches && matches[1];
I say "if you have control over the resulting HTML", because this relies on the HTML being reasonably well formed.
The other method would involve parsing it as a DOMDocument and then extracting what you need, but this would take a lot more and is usually overkill in simple cases like this.
Convert the body within your returned html to a div with a specific ID, then target that id to get the classes of the body (which is now a div.)
modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div id="re_body"')
.replace(/<\/body/i,'</div');
$(modifiedAjaxResult).filter("#re_body").attr("class");
Of course, if the body has an id, this will conflict with it, so an arbitrary data attribute might be less likely to break.
modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div data-re-id="re_body"')
.replace(/<\/body/i,'</div');
$(modifiedAjaxResult).filter("[data-re-id=re_body]").attr("class");
http://jsfiddle.net/N68St/
Of course, to use this method, you'll have to switch to using $.get instead.
$.get("/other-page-01/",function(ajaxResult){
var modifiedAjaxResult = ajaxResult.replace(/<body/i,'<div data-re-id="re_body"')
.replace(/<\/body/i,'</div');
alert($(modifiedAjaxResult).filter("[data-re-id=re_body]").attr("class"));
// the following line replicates what `.load` was doing.
$(someElement).append( $("<div>").html(ajaxResult).find("#site-container") );
});

create html templates textarea or script or div or else

I have seen html templates created using any of the following tags
<textarea>
<script>
<div>
Which one is better and why?
Which of the following way of creating html templates is better and y?
CSS:
.template {
display: none;
}
textarea :
<textarea class="template" id="tmpl1">
<div>adfsdfsdfs</div>
</textarea>
script :
<script type="text/html" id="tmpl1">
<div>adfsdfsdfs</div>
</script>
div :
<div class="template" id="tmpl1">
<div>adfsdfsdfs</div>
</div>
I had faced problem with script tag here
i would suggest none of the above options take a look at Mustache it was created by one of the founders of git hub
http://mustache.github.com/
definitely my favorite way to do html templating
They are all poor choices.
textarea is designed to accept user input
div elements are designed to present content to the user
script elements are designed to hold programs
If you want to embed a template into an HTML document, then I'd write a JavaScript program to store it in a variable (and use a json serializer to generate the JavaScript literal that gets assigned to that variable). That program can then go in a script element.
Alternatively, store the template in a data-* attribute on an appropriate element.

What tag in HTML should I use without special meaning, only to carry meta data?

Is there any meainingless HTML tag to carry additional meta data, for example attributes for JavaScript for specified block/area? like:
<div class="item">
<meaninglesselement data-id="123">
<meaninglesselement data-type="sometype">
<meaninglesselement data-validate="true">
...
</div>
I know that I can move data-* attributes to div class="item" but I want a solution for clean code, even if there will be a lot of parameters.
If it is meta data for the whole document that might be useful for visitors or bots, you should use the meta element. You may only use defined or registered name values (but you could register new ones in the wiki).
For meta data that is only needed for your scripts etc., you may use data-* attributes on existing elements (e.g. body) or you may use the script element:
The script element allows authors to include dynamic script and data blocks in their documents. The element does not represent content for the user.
[…]
When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.
You can place this element in the head or in the document body where phrasing content (like span) can be used, too.
There is an informative example for the use as data block (instead of script):
<script type="text/x-game-map">
........U.........e
o............A....e
.....A.....AAA....e
.A..AAA...AAAAA...e
</script>
So you could use HTML or JSON or whatever format you need.
If you'd want to use HTML, it may (***) look like:
<div class="item">
<script type="text/html">
<div data-id="123"></div>
<div data-foo="bar"></div>
<div>foobar</div>
</script>
</div>
*** (I'm not sure if it has to be a "full" conforming HTML document or if "snippets", like in my example, are allowed, too)
The data applies to the div, the attributes should be on the div. If you want to format your code with one item per line, then you can.
<div class="item"
data-id="123"
data-type="sometype"
data-validate="true">
There are no elements designed for storing meta data that go in the document body.

Mustache JS Templating - How do I embed a variable in a script tag string?

I just started using Mustache and I like it so far, but this has me perplexed.
I am using the GitHub gist API to pull down my gists, and part of what I want to do is include the embedding functionality into my page. The problem is Mustache seems to not want to have anything to do with my dynamic script tag.
For example, this works fine:
<div class="gist-detail">
{{id}} <!-- This produces a valid Gist ID -->
</div>
Additionally, this works perfect:
<div class="gist-detail">
<script src='http://gist.github.com/1.js'></script> <!-- Produces the correct embed markup with Gist ID #1 -->
</div>
If I try to pull these together, something goes terribly wrong:
<div class="gist-detail">
<script src='http://gist.github.com/{{id}}.js'></script> <!-- Blows up! -->
</div>
Chrome Inspector shows this:
GET https://gist.github.com/%7B%7Bid%7D%7D.js 404 (Not Found)
... which looks like to me something is weird with escapes or whatnot, so I switch over to the raw syntax:
<div class="gist-detail">
<script src='http://gist.github.com/{{{id}}}.js'></script> <!-- Blows again! -->
</div>
And I get the same result in Inspector:
GET https://gist.github.com/%7B%7B%7Bid%7D%7D%7D.js 404 (Not Found)
How do I get the correct values to embed in the script tag?
EDIT
I am injecting the template as follows (in document.ready:
function LoadGists() {
var gistApi = "https://api.github.com/users/<myuser>/gists";
$.getJSON(gistApi, function (data) {
var html, template;
template = $('#mustache_gist').html();
html = Mustache.to_html(template, {gists: data}).replace(/^\s*/mg, '');
$('.gist').html(html);
});
}
The actually template is inside of a ruby partial, but it is wrapped in a div (not a script tag, is that a problem?) (that's hidden):
<div id="mustache_gist" style="display: none;">
{{#gists}}
<!-- see above -->
{{/gists}}
</div>
I assume a div is ok rather than a script because in either case, I'm pulling the .html(). Is this a bad assumption?
To avoid automatic escaping in Mustache use {{{token}}} instead of {{token}}.
It seems like your template is in HTML and trying to retrieve the template using html() results in a pre-URL-escaped template to be returned. Try placing your template inside a <script type="text/html"> tag instead.
When you embed your template inside an HTML element that excepts more HTML elements as children, it may get processed by the browser as HTML. Escaping may occur. By using a <script> tag with a non-script content type, you're basically telling the browser not to touch your template.
It looks like your script is getting requested before Mustache has a chance to update the src property. What you want to do is define the template in a way that it's not parsed as part of the DOM. A common approach is to define your template inside of a <textarea> tag. This will preserve formatting and prevent character escaping.
<textarea id="gist-detail-template" style="display:none">
<script src='http://gist.github.com/{{id}}.js'></script>
</textarea>
Now, to instantiate the template:
var template = $('#gist-detail-template').val();
var html = Mustache.to_html(template, yourTemplateData);
Here's an official example: http://mustache.github.com/#demo

Categories