The correct way to load third party scripts? - javascript

With a bit of help from Stackoverflow I've managed to display blog content from Tumblr on my own website.
I've noticed that if the Tumblr site is slow, it effects the page loading speed of my own website.
I found this article on javascript.info. The article recommends using this code to create a variable of the external script URL.
var script = document.createElement('script')
script.src = 'http://ads.com/buyme?rand='+Math.random()
// now append the script into HEAD, it will fetched and executed
document.documentElement.firstChild.appendChild(script)
I (kind of) understand what's happening in the first two lines, but I don't understand how to use the last bit of the code:
document.documentElement.firstChild.appendChild(script)
How would I add the script variable into the src of the script?
<script type="text/javascript" src="URL OF SCRIPT TO GO HERE"></script>
Hope someone can help, this'd be useful for other third party scripts on my site.
UPDATE
Thanks to 'The Spooniest' for helping with this (see thread below).
I was having problems getting this to work with my current page, so I decided to strip it down and create a basic page to see if I could get just this script working.
The code below works, it drops the Javascript just before the </head> tag. Great! However there's somehting that bothers me when I inspect the page (using Dev Tools) I see this warning:
Uncaught SyntaxError: Unexpected token < ?rand=0.9741437959019095:1
Any ideas why this appears? Is it a problem?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script>
var script = document.createElement('script')
script.src = 'http://ads.com?rand=' + Math.random()
// now append the script into HEAD, it will fetched and executed
document.documentElement.firstChild.appendChild(script)
</script>
<title>Demo</title>
</head>
<body>
<p>A basic page</p>
</body>
</html>
UDATE 2
Figured out what the problem was. The URL in the script wasn't a .js file. When I enter a URL linking to a .js file (which I want) it works a treat!

You already added it.
Let's look over the code again:
var script = document.createElement('script')
script.src = 'http://ads.com/buyme?rand='+Math.random()
// now append the script into HEAD, it will fetched and executed
document.documentElement.firstChild.appendChild(script)
The first line creates the element that will become your script tag. The second line sets script.src to a particular URL: in this case it's to an ad site, but you would want to use the URL of your Tumblr code instead. The third line puts the your script at the end of the first tag inside the document element (which in this case means the head).
The magic happens in the first two lines. document.createElement looks at the name of the tag you're creating, in order to figure out the proper class to use for the element: for 'script', that means using HTMLScriptElement. This particular class knows that when you set its src property, that's supposed to go in the src attribute of the script tag. The instance you created remembers this even after you put it into the document, and so that's how the attribute gets there.

document.documentElement.firstChild.appendChild(script)
The above code will add the script to the head tag of your page. As document.documentElement.firstChild will point to head tag.
You don't have to add script variable into src, since it's already taken care by javascript code.
It's generally suggested that javasript files should always be added at the bottom of the page. So that the page loads faster.

Related

How to load a script tag with esmdefine in head using another javascript function

I have a java script function test1.js. The function loads external scripts on demand and injects it in the head. As part of the vendor documentation we need to load few scripts in the html head and One of the external script is loaded as follows
<script>esmDefine(["https://website1.com/web1-component.js"]);</script>
I want to do the same in java script and inject the above line in the html tag.
I tried the following
let scriptElement = document.createElement('script') scriptElement.textContent = 'esmDefine(["https://website1.com/web1-component.js"])' document.getElementsByTagName('head')[0].appendChild(scriptElement);
Tried
scriptElement.innerText, scriptElement.innerHtml etc but nothing worked as expected.
Result expected will be
<html>
<head>
<script>
esmDefine([
"https://website1.com/web1-component.js",
]);
</script>
...
</head>
Any ideas in this regard is appreciated
I guess you're facing this issue because you're trying to append a script tag in your head tag, that has a function call within it, so as soon as your script tag is injected into the head of your page, the page tries to execute the esmDefine function. But there must be some other external script file that has it defined, as you're saying that you've not defined it anywhere on your own. Then in order for this function to execute, the base declaration for this needs to present there, I mean the page's JavaScript renderer should know how to execute this function and the file that has this functions definition, is an external script file that you linked to your page, but how JavaScript rendering works is, it first parses the page (HTML, CSS, JavaScript (everything that is there on the page)), that you've added as inline to the page, not the external files. Then when everything is done loading then it goes on to fetch the external references and add those later to the CSS Object Model & JavaScript Object Model. But since you're adding this function call as internal to your page, it'll immediately try to execute it and will fail since the definition to this function (the external script file) is not yet loaded. You can try appending this script tag (with your esmDefine) to your page's head inside the window's load event listener. This will be fired only when everything on the page, including the dependent external resources are done loading on to the page. This way you'll not encounter this not defined ReferenceError.
I hope this will help you to move forward.
If you want to import a js script in a script tag I think you could import it or use a src="" if you do not need to interact with the script and know how it behaves.
Maybe try something like:
<html>
<head>
<script>
import esmDefine from 'https://website1.com/web1-component.js'
// esmDefine() ?
</script>
...
or :
<html>
<head>
<script>
import { esmDefine } from 'https://website1.com/web1-component.js'
// esmDefine() ?
</script>
...
or :
<html>
<head>
<script src='https://website1.com/web1-component.js'/>
...

Adding a JavaScript embed to HTML

I am given this code which should display an embedded small coupon version of this page https://weedmaps.com/deals#/1118217:
<script type="text/javascript">var coupon_id = 17811;</script>
<script type="text/javascript">var coupon_type = "deliveries";</script>
<script type="text/javascript" src="https://weedmaps.com/embed/coupon.js"></script>
I do not know how to add the JavaScript to the HTML correctly. I have placed the following scripts in the head section. But I don't understand how to have the coupon generate in the div I want it to. I have tried calling the JavaScript function, but I've never worked with JavaScript before. Could someone please help me embed this coupon.
I've taken a look at your script and first of all: it definitely should be placed inside the document and not into the <head> section because coupon.js is writing out html at the placement of the coupon.js script import.
In theory you just need to place the script and it should work but there are some problems:
You need to execute it on a web server - when running as a plain html file the script just tries to find the libraries in your file system which does not work.
It still would not work because it would still try to find some resources at your web-server. In mycase it the script tried to load http://localhost:63342/restpoints/deliveries/17811/deal which will not work
To prove 2. just try https://weedmaps.com/restpoints/deliveries/17811/deal with the correct domain. Then you are receiving correct JSON which is used to fill the coupon pane.
=> Consequently the script you were given has problems if it should be executable from domains different from "weedmaps.com"
Javascript can be between head tag but it advisable to put it below before the body closing tag, to allow your page contents loads first before loading javascript. Just import your javascript. and call out. Hope this was helpful.
<!DOCTYPE html>
<html>
<head>
</head>
var coupon_id = 17811;
The JS indicates it is looking for an element with an id of #weedCouponPane. Do you have this in your html? i.e.
<div id="weedCouponPane"></div>

Where to insert JavaScript Libraries and CSS in my HTML code?

I am little new to web development and when I was searching internet about other topics, I have seen many people has put popular JS Libraries in Different Places of their websites.
eg: Inserting JS Libraries on the Very Beginning or Start of the <head> </head> section. (Before loading any JS Code or a CSS File)
eg: Inserting JS Libraries on the End of the <head> </head> section. (After loading all JS Codes and CSS Files)
eg: Inserting JS Libraries on the End of the <body> </body> section. (After loading all JS Codes, Texts, Images, Videos, CSS Files etc...)
So my question is this.
What is the best practice for inserting (where) following JS Libraries, Plugins and CSS Style Sheets to a web page for the most faster loading times and other advantages? - Please mention the reason -
JQuery and it's Plugins
Bootstrap 3.js
Modernizr.js
Angular.js
And another widely used JS Libraries which I couldn't mention here...
Normalize.css
reset.css
bootstrap.css + more
Thank You..!
There is no so called "standard" method. The choice of where to put the lines boils down to one question: When will I need the library?
You see, web files loads line by line, let's take the following as an example of what I mean:
<script>
document.getElementById("target").innerHTML = "changed"
</script>
<p id="target">unchanged</p>
#target isn't altered because the script was loaded before the element did. Web files loads procedurally. When the line of JavaScript is loaded. It is executed immediately, but the target element isn't. So it couldn't change the element.
Even with jQuery, there is the same problem:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#target").text("changed");
</script>
<p id="target">unchanged</p>
Therefore, we often use $(function(){}).
Back to the loading problem
People who put their <script> tags or <link> tags in the body (in front) or in the head, wanted to execute the script immediately, sometimes they won't use $(function()) or document.onload
People who put their <script> tags or <link> tags in the body (in the end) wanted to ensure all elements are loaded then execute the script or load CSS.
Conclusion
You should load independent resources such as jQuery first, then load dependent resources such as jQuery plugins. Then you try to decide when you want the resources to start loading, then put the lines in places.
You should put CSS links in the <head> tag because you don't want visitors seeing unstyled content before loading the CSS files.
If you can't decide or don't care about the time, put every <script> and <style> tags in the <head>.
Here is another post you might be interested in: Load and execution sequence of a web page?
CSS can added inside header tag & but put all JS Libraries and custom files just before closing closing body tag
<body>
//other tags
<script> All Scripts here </script>
</body>
By doing so you wont have to check if DOM content has loaded.
It decrease page loading time.Otherwise a js need to be completely loaded before DOM loading.
It also makes sure that all events are attached properly to DOM element.
I think this address all your concern specially the third one
CSS Sheets go in the < head >. The order of the CSS files matter so libraries should be put in first then you can put in the specific ones you have.
Javascript links go in the < body > but place them at the very end. That way your HTML content loads first then the JS loads and it will recognize all your selections. It is more efficient to do it this way.
The most important thing to note when placing your css and script tags is that the order you place them determines the order they are loaded in and if style or code is loaded later it over writes the code written before. So if you have css styling that assigns different styles to the same attributes of the same element then it is the one loaded later that takes effect. And with script tags it's important to remember that for dependency reasons. You should load the dependencies first so that they are there for the other scripts to use. Aside from that normally css tags are in the head and script tags at the bottom of your body element

Adding link to head does not reflects in page source

I have used below code to append link tag in head section. It is having below behavior
1. I am able to see the attached link tag in firebug but not in page souce
2. my head section belongs to a different jsp file
Can i get some tips on this?
Below is the script I have used in body section
<script type="text/javascript">
var appendHTML= "<link rel='next' href='http://test.com'/>";
$('head').append(appendHTML);
</script>
Thanks,
Abhishek
You are not alone witch such kind of task on SO. Try to find around and you will see same themes - How to load up CSS files using Javascript?

Ad Script Not Working

So I have this thing called "AdHitz" on my website (I'm not old enough for AdSense), and I need to put ad code on every page in order for it to work. The thing is, you have to change the script link from time to time, and I didn't want to have to edit every single webpage every time the link changed, so here's what I did:
Original:
<script type="text/javascript" src="http://adhitzads.com/745025"></script>
Newer:
<script id="ad1"></script>
In the CSS Stylesheet file:
#ad1 {
type="text/javascript";
src="http://adhitzads.com/745025";
}
The thing is, the ads are no longer showing up! What should I do?
Here do this.. Include this script tag on each one of your pages:
<script type="text/javascript" src="ads.js"></script>
Then make a file called ads.js and put this in it
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://adhitzads.com/745025";
document.head.appendChild(script);
Then everytime your ad company changes your url, just open ads.js and change the URL there.
Your best option would be to use a server side include to put the script on each page.
You could put your script into a script file (ad-script.js, the name does not matter) and include it in your pages like this:
<script src="ad-file.js">
You could also create a file like ad-file.html and then paste the script into it. Then include it in each page like this:
<!--#include file="ad-file.html" -->
Also, CSS is a styling language, so it cannot handle scripting.
You seem to be confused about how CSS works. While your CSS correctly targets elements with the ID of "ad1", CSS is formatted like "display: none;" and not with equal signs. Secondly, 'type' and 'src' are more than likely not valid CSS attributes that you can modify.
I understand that you are worried about having to change this link on multiple pages. If you want another way to solve this problem, you can use PHP for your website, and make a PHP file for the portion of your website that has the Javascript includes. Then all you have to do is edit the one PHP file and every site will include that one file. Alternatively, you can use a better and free text editor, such as KomodoEdit, to do a mass replace with very little trouble or time required.

Categories

Resources