How to make the browser run JavaScript code injected by DOM manipulation? - javascript

I want to serve a little HTML snippet that other pages can include.
The HTML content would look something like this:
<div id="coolIncludable" style="display:none"> <!--be invisible until you are finished initializing -->
<div>Cool stuff here</div>
<div>More cool stuff and so on...</div>
</div>
<script src="http://somehwere/jquery.js"></script>
<script src="http://somewhere/something.js"></script>
<script>
$(function(){$('#coolIncludable').show();});//<- actually contained in a script file, just for illustration
</script>
I'm planning to use the method detailed here: https://www.w3schools.com/howto/howto_html_include.asp to do the actual including. Let's say the page looks something like this:
<html>
<head>
</head>
<body>
<H1>Content before snippet</H1>
<div id="registerWrapper" html-include="http://somehwere/snippet.html">
No content loaded
</div>
<H1>Content after snippet</H1>
<script type="text/javascript" src="http://somehwere/html-include.js"></script>
</body>
</html>
The HTML snippet gets loaded and embedded all right, but the JavaScript that comes with it never gets executed. Is there a way to embed content including scripts that makes sure they are executed?
I don't expect to control the embedding page, so I cannot rely on it having jQuery or anything else loaded. I therefore avoided using jQuery in the embedding function and restricted myself to plain JavaScript. Loading jQuery is one of the things the <script> tags at the end of the snippets would do.

Since you are using jQuery you can use it's built in load() method to do what you want
Something like:
HTML
<div class="include" data-include="page2.html"></div>
JS
$('.include').each(function(){
const $el = $(this), url = $el.data('include');
$el.load(url)
});
Then make sure the script tag for the new content is below that content.
Simple working demo

In retrospect, my mistake is glaringly obvious:
What does the line $(function(){$('#coolIncludable').show();});
do? does it execute $('#coolIncludable').show();? No it doesn't. It registers a callback to do so that gets triggered by the 'load' event, which already has fired, and won't fire again.
On the other hand, that's really a moot point because the code never even gets executed.
Here's what I learned about dynamic loading of javascript
Injecting script tags directly does not work
script tags injected by setting element.innerHtml do not get executed
<div id="snippet">
...
</div>
<!-- neither of these will be executed -->
<script type="text/javascript">alert("stuff");</script>
<script type="text/javascript" src="http://somewhere/script.js"></script>
Creating script tags dynamically does work
What does work is dynamic tag generation the way it is described in this article: JavaScript Madness: Dynamic Script Loading
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.type= 'text/javascript';
script.src= 'helper.js';
head.appendChild(script);
//At this point (or soon after) the code in helper.js will be executed
You would do that in your loading script. My loading script looks something like this:
function importJsFiles(){
const scriptFiles = ["http://somewhere/jquery.js",
"http://somewhere/stuff.js",
"http://somewhere/bootstrapSnippet.js"];
for (let i = 0; i< scriptFiles.length; i++){
importJsFile(scriptFiles[i]);
}
}
function includeSnippet(){
//See https://www.w3schools.com/howto/howto_html_include.asp
//We still have to do it without jQuery,
//because at the time this executes the injected jquery.js
//hasn't run and we do not yet have jQuery available
}
importJsFiles();
//At this point, all script tags are created, but the scripts are NOT loaded yet
includeSnippet();
//At this point, the dom is in its final shape
bootstrapSnippet(); //<- This won't work, because the script tags injected by this code won't be evaluated until after this file/function/whatever returns
//bootstrapSnippet.js
function bootstrapSnippet(){
alert("Snippet JS running")
if (window.jQuery) {
alert("JQuery is avaliable"); //<- This will fire, because the new script
// tags are evaluated in order, and we put the
// jquery.js one before the bootstrapSnippet.js one
}
//So now we CAN do this:
$('#coolIncludable').show();
}
bootstrapSnippet();
There are many more interesting ideas and details in this post that I picked the link above from. I hope someday I'll find time to explore them all.

Related

Are DOM elements preceding a <script> tag guaranteed to exist before the script runs?

Does the HTML spec guarantee that DOM elements appearing before a <script> tag are present before the content of that script is executed (and can be manipulated by that script)?
This works in all browsers I've tested, but I'm not sure whether it's legal:
<main hidden>Hello, world</main>
<script type="text/javascript">
document.querySelector('main').hidden = false; // no error thrown
</script>
I know that the script will execute immediately, blocking parsing, unless it has the async or defer attributes.
But does the parsing up until this point guarantee that the prior elements are in the DOM and ready to be manipulated, or is it safest to wait for DOMContentLoaded?
As far as I know, it will run just after parsing the previous node. You can use even document.write function to feed the parser with code.
As you can try below, it can even close tags. It directly feeds the output from document.write() to the parser.
Foo
<script>
document.write("<strong>bar</strong>")
</script>
<em>something
<script>
document.write("weird</em>")
</script>
here.
You can access the DOM in scripts even when the loading is in progress, but I would personally avoid it. As you can see below, element that was not yet closed can be accessed.
This works:
<em id="foo">foo</em>
<script>
document.write(document.getElementById("foo"))
</script>
<hr />
<em id="unclosed">unclosed element
<script>
document.write(document.getElementById("unclosed"))
</script>
</em>
But avoid long-running scripts, because the parser (and therefore rendering) will stop and it can be unpleasant if the scripts does its work for few seconds.
In this example, you can see that you can hide, and even remove, the element even just after the opening tag:
<p id="toHide">
<script>
document.getElementById("toHide").remove()
</script>
This is hidden.
</p>
This is not hidden.

Loading Section not disappearing on first load

I made a loader that uses css and javascript to play an animation. On loading the site for the first time the animation sometimes doesn't play leaving a blank white screen. I believe it has something to do with caching on the second load that makes it work. Thanks in advance.
HTML:
<section id="loading">
<div class="circle spin"></div>
<img src="src/j2.svg" alt="J2 Logo">
</section>
<link rel="stylesheet" href="css/loading.css">
<script type="text/javascript" src="scripts/loading.js"></script>
loading.css:
https://pastebin.com/E16PMTtQ
loading.js:
https://pastebin.com/1X09KatC
The websites link is https://j2.business
With a quick look at your code it looks like all code is executed when the javascript-file gets loaded. This could be a timing-issue (your javascript-file is retrieved faster than your HTML-page: the elements it wants to act on are not available yet).
With jQuery you can quickly solve that by embedding your variables and functions in this holder:
$( document ).ready(function() {
// place code here, the document is waiting
});
Because you are not using jQuery you could use this:
add the "defer" attribute.
<script type="text/javascript" src="scripts/loading.js" defer></script>
This should be enough, specs found here:
https://www.w3schools.com/tags/att_script_defer.asp
Or if you want only some functions executed when the document is loaded you could use the function which all browsers support:
(function() {
// place code here, the document is waiting
})();

Loading jquery in the last position

I offen heard that loading jquery as last element is a good idea because this way a web page loads faster. At the same time I have a script in the header which shows error:
$(document).ready(function () {// Uncaught ReferenceError: $ is not defined
...
}
Should I move jquery loader before the script or I need to change this script some way?
Your concrete issue stems from the fact that you execute statements that use jQuery (i.e. they execute $, which is a function in the jQuery library, also called "the jQuery function" because jQuery is an alias) before it is loaded.
True, it is typically recommended to load scripts last, but that still means the scripts have to be loaded in the correct order, with usually jQuery before your own scripts using jQuery.
If you really want to load your own scripts before jQuery for some reason, you need to defer its execution and have a third helper script to run it, e.g.:
// script.js
(function() {
function myLibraryMainFn() {
$('div').text('simulating work, utilizing jQuery');
}
window.myNamespace = {
run: function() {
myLibraryMainFn()
}
};
}());
<!DOCTYPE html>
<html>
<body>
<div></div>
<script src="script.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
// Run your script now:
window.myNamespace.run();
</script>
</body>
</html>
Always refer library file first(in your case jQuery), then use it next..For page load and performance add it before body end tags of your HTML

Best way to fire events when single elements in the document becomes ready

I'm developing a web application that because of performance concerns is heavily reliant on Ajax functionality. I'm attempting to make parts of each page available while longer running modules load.
The issue is that I want to kick off the Ajax requests as soon as possible (in the head of the document). This part works fine; the issue is on rare occasion, the Ajax call will come back before the area that I want to load the Ajax data into is present on the page. This causes the data to not be loaded.
To get around the issue I started using script tags below each of my containers that resolve a JQuery promise to let the code know that the area is available.
EDIT: I want to load the data into the area as soon as it becomes available (before full document load).
The current pseudo code looks like this:
<head>
<script>
var areaAvailablePromise = new $.Deferred();
$.when(areaAvailablePromise, myAjaxFunction()).then(function(){
// load data into the element.
});
</script>
</head>
<!-- much later in the document -->
<div class="divIWantToLoadAjaxContentInto"></div>
<script>
areaAvailablePromise.resolve();
</script>
My question is: is there ANY better way to handle this situation? Every one knows that inline scripts are blocking and are bad for performance. Also, I feel that this is going to lead to cluttered code with micro-script tags all over the place.
Put your (whole) <script> tag just after the element.
HTML is parsed from top to bottom, so the element will be loaded already.
No. There really is no better way to my knowledge.
<!doctype html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="q.min.js"></script>
<script>
var elD = Q.defer();
var dataP = Q($.ajax(…));
Q.spread([elD.promise, dataP], function (el, data) {
…
}).done();
</script>
</head>
<body>
…
<div id="foo"></div>
<script>elD.resolve($("#foo"));</script>
…
</body>
</html>
you can use:
$(document).ready( handler )
(recommended)and also has contracted form:
$(handler)
exemple:
$(function(){
alert("OK");
})
read more: http://api.jquery.com/ready/

How to detect whether a plugin or script has already been loaded without using eval() or requireJS?

I'm working on a plugin that allows to inject 3rd party code into a page (either as iframe or directly into the DOM).
My problem is "direct injections", because I need to make sure, I don't add any <scripts> additional times, if they are needed in my main page and in a page I'm loading and injecting.
For example (and I can't use requireJS), my page.html looks like this:
<html>
<head>
<script type="text/js" src="jquery.js"></script> // exports window.$
<script type="text/js" src="foo.js"></script> // exports window.foo
</head>
<body>
<!-- things that make foo load anotherPage.html and append its content here -->
</body>
</html>
with anotherPage.html
<html>
<head>
<script type="text/js" src="foo.js"></script> // exports window.foo
</head>
<body>
<!-- stuff that also runs on FOO -->
</body>
</html>
Page loading is done via Ajax and when I'm processing the data returned by my request for anotherPage.html I end up with a list of all elements after doing this:
cleanedString = ajaxResponseData
.replace(priv.removeJSComments, "")
.replace(priv.removeHTMLComments,"")
.replace(priv.removeLineBreaks, "")
.replace(priv.removeWhiteSpace, " ")
.replace(priv.removeWhiteSpaceBetweenElements, "><");
// this will return a list with head and body elements
// e.g. [meta, title, link, p, div, script.foo]
content = $.parseHTML(cleanedString, true);
// insert into DOM
someTarget.append(content);
This is where I'm stuck trying to detect whether a script I'm about to append to the document is already there.
I cannot go by the src, because the filename may differ and a script may be hosted on a different domain (with Access-Control-Allow-Origin correctly set). I also don't know, what and if the script I'm about to append returns a global I already have defined and I can't/don't want to use eval() to find out.
Question:
Is there any way to identify whether a plugin or script that may return a global is already "on" a page, when I only have the "non-appended" <script> element available?
Thanks!
here is an example of my self-enclosed module pattern, i call it a "Sentinel":
(function wait(){
if(!self.$){
if(!wait.waitingJQ){
wait.waitingJQ=true;
addScriptTag(JQUERY_URL);
}
return setTimeout(wait, 44);
}
doStuffThatNeedsJquery();
}());
The sentinel pattern work from anywhere (internal or external), doesn't care about script loading order, and works with ANY script loading library. you can list additional depends below the jQuery fork in the same manner, just put your greedy code at the bottom of the sentinel wrapper function.

Categories