A method to get specific exports when using <script src=""> - html

I'm making a site with Preact & Tailwind. In the code here (I know it doesn't have head, body, e.t,c but that isn't relevant to the code):
<script src="https://unpkg.com/tailwindcss-jit-cdn"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/preact/10.11.2/preact.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/htm/3.1.1/htm.js"></script>
<script>
htm.bind(h)
let component = htm`<p>Hello World</p>`
</script>
htm and h are parts of the Preact and HTM cdn. How do I get htm and h from the preact/htm cdns?
I don't want to use a node_modules, as i want it to be a copypastable template html to use anywhere, like WordPress, replit, codepen, e.t.c. I also don't want to use as the way my code is setup it would look weird and bad to read.

Adding a dependency (or dependencies) via <script> adds those to the global scope. h, in the example above, is undefined as you have not specified where it comes from.
<script src="https://unpkg.com/tailwindcss-jit-cdn"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/preact/10.11.2/preact.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/htm/3.1.1/htm.js"></script>
<script>
let html = htm.bind(preact.h)
let component = html`<p>Hello World</p>`
</script>
(Adjusted code, as htm.bind alone will not work. Need to assign & use the result).
This, however, is less than ideal in the modern age of ESM. Messing with globals is just rather unnecessary. Instead, use the following:
<script src="https://unpkg.com/tailwindcss-jit-cdn"></script>
<script type="module">
import { h } from 'https://cdn.skypack.dev/preact';
import htm from 'https://cdn.skypack.dev/htm';
let html = htm.bind(h);
let component = html`<p>Hello World</p>`;
</script>
Or, even better yet, use htm/preact export to skip manually binding altogether:
<script src="https://unpkg.com/tailwindcss-jit-cdn"></script>
<script type="module">
import { html } from 'https://cdn.skypack.dev/htm/preact';
let component = html`<p>Hello World</p>`;
</script>
Unpkg has a number of issues (very difficult to fix, if not impossible. Not a criticism, unpkg was built in a different time) regarding ESM usage, specifically for Preact, resolving package.json "exports" and sometimes duping the Preact instance. This is an issue for hooks, as they require a singleton by design. This is why I'd recommend Skypack or esm.sh. They're built for ESM and work brilliantly.

Related

Avoid html form classic behaviour with ajax [duplicate]

I noticed that the <script src="..."></script> tag does not allow you to use JavaScript within it, such as:
<script src="myFile.js">
alert( "This is a test" );
</script>
And this does not work, nor does it throw an error in FireBug, why is this happening, why do we have to add extra <script> tags to allow for JS to be used on the form itself?
Example
I have a file, found # script/addScript.js from my root, and this contains:
function addScript( $src )
{
var script = document.createElement( 'script' );
script.type = "text/javascript";
script.src = $src;
document.getElementsByTagName( 'head' )[0].appendChild( script );
}
This is designed to allow me to add scripts to the DOM quickly and effectively, so I tried to do this:
<script src="script/addScript.js">
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
But it did not work, so I have to do this instead:
<script>
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
A script element loads a single script.
It can do that from either a URL or from inline, but it still loads one script; it can't use both types of source at the same time.
If you try to include both, the inline script will be ignored:
<script src="example.js">
this_is_ignored();
</script>
… so you need multiple script elements.
<script src="example.js">
</script>
<script>
this_is_NOT_ignored();
</script>
It is worth noting that the content of the script element will still exist in the DOM, so some people use it to store data in it which the JS referenced by the src will read. data-* attributes are (arguably) a cleaner approach to that though.
Each <script> element contains one piece of executable javascript code. If you use a src attribute to load an external file, that is the piece of executable js for that element, otherwise it is the code placed between the <script></script> tags. If you try to do both, then you're attempting to associate two pieces of executable code to one script element and that is not the behavior of the script element so the browser's javascript engine ignores the inline code and executes the included file code.
As to why this is the case, it was likely a design choice by whoever established this standard. By creating a one-to-one relationship between code pieces and <javascript> elements there is no ambiguity about what code is being run or its priority.
Therefore in your case you will first have to load your external file...
<script src="script/addScript.js"></script>
and then call any functions provided by it.
<script>
addScript( "script/obj.js" );
addScript( "script/home/login.js" );
</script>
For reference, this is generally how all javascript libraries are loaded within a webpage.

WordPress enqueue JS, jQuery and other libraries

Here’s what I do in an ordinary html file.
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/test.js"></script>
Now, I’d like to see this reflected in WordPress. So in my functions.php I do this:
function theme_files(){
wp_enqueue_script('jquery',get_theme_file_uri('js/jquery-3.3.1.slim.min.js'),NULL,'1.0',true);
wp_enqueue_script('popper',get_theme_file_uri('js/popper.min.js'),NULL,'1.0',true);
wp_enqueue_script('bootstrap',get_theme_file_uri('js/bootstrap.min.js'),NULL,'1.0',true);
wp_enqueue_script('ui',get_theme_file_uri('js/jquery-ui.min.js'),NULL,'1.0',true);
wp_enqueue_script('ownJS',get_theme_file_uri('js/scripts.js'), array('jquery'), '1.0',true);
}
add_action('wp_enqueue_scripts','theme_files');
Unfortunately it doesn’t work. I already found out that its not the dependency in my own js (scripts.js). It doen’t matter whether I do NULL or array(‚jquery‘). Also, I tried to only enqueue my own js without the others. Doen’t seem to change a thing.
Suprisingly, when I do alert(’test’); in my scripts.js it does pop up. But when I do
$(„#idOne“).click(function(){
alert(‚hello‘);
});
Nothing happens when I click on the element with the id=„idOne“
Even when I do pure js
function sayHi(){
alert(‚Hi‘);
}
var one = document.getElementByID(‚idOne‘);
one.addEventListener(‚click‘,sayHi, false);
it doesn’t do a thing ether. What do I do wrong?
Thanks!

Read the contents of a link or script tag using src/href

How can I read the contents of a file using
<link href='path/to/file'/>
I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.
I understand that lesscss.js lib uses the without an ajax get call.
From: http://lesscss.org/#using-less
<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>
I need to include some templates into the page, and the sooner they are loaded the better, ( vs doing it after jquery and js has loaded)
Thanks!
I understand what you mean with before jquery. But what do you mean with "before js".
When you load less.js (which does NOT depend on jQuery) the browser runs less.js before jquery has been initialized. Notice that less.js requires JavaScript.
You can read the content of such a file leveraging a XMLHttpRequest. A basis example which shows you how to do this can be found at: How to show the compiled css from a .less file in the browser?
Regarding less.js, you can find the source of that file at: https://github.com/less/less.js/blob/master/dist/less-1.7.4.js
I understand that if one adds the attribute type="text/css" then they can be read using document.styleSheets but I have a hard time figuring out how to get the content of that element though.
Globally less.js uses two steps to do that:
first it will built a list of paths as follows:
//
// Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
//
var links = document.getElementsByTagName('link');
less.sheets = [];
for (var i = 0; i < links.length; i++) {
if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
(links[i].type.match(typePattern)))) {
less.sheets.push(links[i]);
}
}
Then reads the content of these files by using a XMLHttpRequest too. See the doXHR function at line 7720 of less-1.7.4.js.

How to add bootstrap JSON content into a html file in Play Framework?

In the Application.java I get all users
public static void index() {
renderArgs.put("users", Users.getAll()); //getAll() returns gson.JsonArray
}
In index.html I bootstrap this users like this:
<script type="text/javascript">
Users.reset(&{users});
</script>
But the JSON is rendered like this:
[{"id":"1234" ...
How can I get the JSON to be formated as JSON?
Maybe this will help:
<script type="text/javascript">
Users.reset(&{users.raw()});
</script>
From playframework documentation:
raw()
Returns the object without template escaping.
Returns: play.templates.Template.ExecutableTemplate.RawData.
When you're using Backbone.js, they recommend you to use this style of bootstrapping your collection(s). I didn't really like this approach though, so I used an alternative: to bootstrap your Collections, simply wrap them in a manual $.getJSON() call to initialize them. For example:
<script type="text/javascript">
$(function() {
$.getJSON("#{controllers.MyJsonApiController.getStuff()}", function(data) {
Users.reset(data);
});
});
</script>
Note: the exact syntax of the Users.reset() call may not be correct, you may have to define the collection in the window scope, depending on your requirements.
An even better approach I found — when you're also using the Backbone.js Views — is to encapsulate your Collection management in your View objects. This way, when you render your page, the only thing you have to do is render the view and this will do its own initialization.
Update: corrected the fetch() call to a reset(data) call.

Using <script> in CSS

Is there any way to write script in css and call or execute it whenever required ?
I need a <script> tag to be executed .
i need something like this..
css code
#execute{
<script> ..some script.. </script>
}
so whenever i use
<html>
.
.
.
.<div id="execute" />
.
.
.
.
</html>
so if i change the script changes will be reflected everywhere.
Is it possible?
EDIT:
Is it possible to keep my <script></script> tags inside some js file and i will host it. and then i will call some function() from my HTML so that the script will be executed everywhere i need it.
Can someone show me any example, tutorial how i can do it.
I don't have much information about the Js file and how the function should be called.
Thank you all
Does it have to be in CSS? jQuery is a great, simple way to do what you're asking. You put all your style information in the CSS (what it's intended for) and keep your javascript in the html or a .js file. Take a look at http://jquery.com. The code would look something like this
$(function() {
$('#execute')
.someCoolFunction()
.anotherCoolFunction();
});
You use $(function() { /* code */ }); to run the code when your document is ready, and you use $('#execute') to grab the element with the execute tag. You can then do a lot of cool javascript really easily with that jQuery element.
No, you cannot mix CSS and Javascript this way. Why would you want to?
If you simply want a common JavaScript include, do it like this:
<script type="text/javascript" src="yourscript.js"></script>
You can't do this in standard CSS.
There is a way in which you can run code from within the CSS context, using a technology called 'Behaviours', referencing an HTC file (which is basically Javascript) in the stylesheet.
However, this technology is non-standard, and only exists in IE. It is therefore only really used to write hacks to make IE support features that it doesn't have which are in other browsers. An example of this in use is CSS3Pie.
If you're working on a site which will never be used in any browser other than IE, and you're happy to use a non-standard technology, then you may consider this to be the exact answer to your question. However I would strongly recommend you don't do this.
More realistically, you should be using a Javascript library such as JQuery, as the functionality you describe is pretty much standard fare for JQuery.
With JQuery, you would write code like this (in a normal script block, not in the CSS!):
$('.execute').each(function() {
/* your code here; it would be run for each element on the page with the class of 'execute' */
}
As you can see, it uses a CSS-style selector syntax to select the elements to work with.
(also NB: I've used execute as a classname here, not as an ID, because you imply that you want more than one of them -- note that you should never use the same ID more than once in any HTML page; it is invalid. If you need the same thing several times, use a class.
JQuery has functionality to watch for changes to elements, respond to events such as clicks or mouse over, and much more. Other similar libraries such as Prototype, MooTools and Dojo would also be able to do a similar job.
Hope that helps.
[EDIT]
Given the edit to your question, can you not just place the advertisment <script> tag inside the <div> on the page where you want it?
So with JQuery, you could write something like this to run your ad in each place you want it:
HTML:
....
<div class='execute'></div>
....
<div class='execute'></div>
....
Javascript code (remember to also include the JQuery library, or this won't work):
$(document).ready(function () {
$('.execute').each(function() {
advertisement(this); //change to whatever the advertisement script function is called.
});
});
Hopefully that will get you started. I can't really help you much more without knowing more about the advertisement script, though.
Also, the people who supplied the advert script should be able to tell you how to use it.
I believe a Javascript library like JQuery or Dojo is what you are looking for. It will allow you to add event handlers on tags with certain CSS attributes, which will behave exactly like what you are trying to do right now.
EDIT
Here is an example with Dojo pulled from the Google CDN that will popup an alert window when you click on any <div class="execute"></div> block:
<html>
<head>
<style>
<!--
.execute { background-color: red; height: 25px; }
-->
</style>
<script src="http://ajax.googleapis.com/ajax/libs/dojo/1.6.0/dojo/dojo.xd.js" ></script> <!-- load Dojo from Google CDN
<!-- Let's register a onClick handle for any .execute div. -->
<script>
dojo.ready(function() // Dojo will run this after being initialized
{
// Get A list of all tags with id execute and add a event onClick
dojo.query(".execute").connect("onclick", function(evt)
{
alert("Event triggered!");
// ...
});
});
</script>
</head>
<body>
<div class="execute">Click me 1</div>
<br /><br />
<div class="execute">Click me 2</div>
</body>
</html>
Edit 2
This example uses an onClick event but Dojo (JQuery) allows you to do much more things. For instance if you wanted to dynamically add an image or something onLoad inside .execute divs, you could do it with Dojo (JQuery) in a similar way to this.
Doing it with a library saves you a lot of effort, but if you still want to write and call your own functions from javascript files, this is a rough idea of how you would do it:
// myScript.js
function foo()
{
// ...
}
// page.htm
<html>
<head>
<script src="path/to/myScript.js"></script>
</head>
<!-- ... -->
<div class="execute">
<script>
<!--
// Call foo()
foo();
-->
</script>
</div>
<!-- ... -->
It doesn't really make sense to abstract a script into CSS like that, and even if it was a good idea, it can't be done.
Why do you need to run the same script over and over in different places? Consider whether or not there might be a better or simpler way to do whatever it is you're doing.
Plus, when you include a script with the src attribute in the script tag, if you modify the script's source file, the changes persist everywhere.
No, but you can use script to alter the CSS properties of any element in the DOM.