Script src javascript - javascript

What is the difference between this code
var head=document.getElementsByTagName('head')[0]
var script=document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', "http://your-script.com/address-here.js")
head.appendChild(script)
and this code
<script type="text/javascript" src="http://your-script.com/address-here.js">
</script>
Thank you.

The javascript at the top is going to append a new element to the first head tag of the document that should equal out to <script type="text/javascript" src="http://your-script.com/address-here"></script> (or close to). The only difference is that the browser will load the HTML version as soon as it comes across it whereas the JS won't be loaded until the element is done being appended.
As #lostsource mentions this would be typically used to load a dependency script or used to bring in polyfills, e.g. if(!someJSFeatureIWant) {//import the script here}.

The first one is normally used as a way to include additional Javascript files required by a Script. (it is just dynamically creating a <script> tag like the second code sample)
For example you might include the core functionality in a main.js file, then depending on user interactivity you decide to include other scripts. (eg. graphics.js, forms.js etc..)
The same approach is also used to make JSON-P requests by dynamically including a url which returns a JSON 'padded' response. With the main advantage over iframes and regular XHR requests being that <script> tags are not affected by the same origin policy.

One is JavaScript and will add a script to the DOM after it has been created. The other is HTML and will add a script to the DOM while it is being created.

Essentially, both load a js file, but the first sample effectively creates the other on demand.
var head=document.getElementsByTagName('head')[0]
var script=document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('src', "http://your-script.com/address-here.js")
head.appendChild(script)
You would generally use this for loading external code into a page on the run (after it is created). This specific syntax used in the example also pollutes the global scope and should not be used as is.
<script type="text/javascript" src="http://your-script.com/address-here.js">
</script>
This is the natural HTML syntax for loading script files. If the page code is under your control, you have no reason to ever use anything other than this unless in special circumstances that demand it or for optimisation purposes.

Related

Run external javascript file on load

We made a website through webnode.nl, because we hadn't enough time to make a website using html. Now we added a widget using a external site using a script tag with the link to this site. But through this widget the page is loading slow. Now I had the idea to run the script after the page is loaded. But I can't access the code of the widget and I can't access the html of the website. I can only access the code block in which I pasted the script tag.
The script tag:
<script type="text/javascript" src="http://mycountdown.org/countdown.php?cp2_Hex=d21a1a&cp1_Hex=F9F9FF&img=-3&hbg=&fwdt=420&lab=1&ocd=My Countdown&text1=Valentijnsdag!&text2=valentijnsdag!&group=My Countdown&countdown=My Countdown&widget_number=3015&event_time=1455408000&timezone=Europe/Amsterdam"></script>
Can someone help me?
PS: English is not my first language, so I don't know if my English is correct
Place it at the end of the <body> and add async to the script tag i.e.
<script async src=""></script>
More info here: http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html There is also the defer attribute.
Typically you want to use async where possible, then defer then no
attribute. Here are some general rules to follow: If the script is
modular and does not rely on any scripts then use async. If the script
relies upon or is relied upon by another script then use defer. If the
script is small and is relied upon by an async script then use an
inline script with no attributes placed above the async scripts.
Edit
You may be better using Defer:
defer downloads the file during HTML parsing and will only execute it
after the parser has completed. defer scripts are also guarenteed to
execute in the order that they appear in the document.
if you can write script blocks then write the following in whatever you are allowed to use.
<script>
// Create a <script ...></script> element
var widget = document.createElement('script');
// Set src="URL_of_widget"
widget.setAttribute('src', 'http://mycountdown.org/countdown.php?cp2_Hex=d21a1a&cp1_Hex=F9F9FF&img=-3&hbg=&fwdt=420&lab=1&ocd=My Countdown&text1=Valentijnsdag!&text2=valentijnsdag!&group=My Countdown&countdown=My Countdown&widget_number=3015&event_time=1455408000&timezone=Europe/Amsterdam');
// Set async
widget.setAttribute('async', 'async');
// Insert <script> as the last element child of <body>
document.body.appendChild(widget);
</script>

Read content of external script tag with jquery

A common pattern for loading backbone templates is something like:
<script type='text/template' id='foo'>
my template
</script>
----
var whatever = $('#foo').html();
I would like to include the script in an external file like so:
<script type='text/template' id='foo' src='myTemplate.tpl'></script>
But the html() of foo is now empty.
I watched the browser pull the template file down, but I am not sure if it is in the page dom or not. Is there a simple way to reference the content of the script in javascript, or did the browser simply ignore it and throw out the result?
I think to actually execute externally loaded script you have to do an eval() of the contents. You're not adding it to the DOM really since it's script, you're adding it to the JS runtime. There might be other ways of doing it but eval() is generally considered a security hole since malicious code could be evaluated.
What I tend to do is generate template sections on the server so I know all my JS is there when the DOM is ready.
If the point is execute an action just after the script has been loaded you can put a onload attribute on the script tag. If you want to download the content in runtime, then you could use the async download strategy (like Gats pointed).
It´s important keep in mind some important points when using templates for jquery templates in external files, there is an interesting article about jquery templates with external files, you must check it.

What is the most ideal way of loading javascript files?

What is the most ideal way of loading javascript files? Also, I want to make sure that order of the javascript files should be maintained. If I have
<script src="javascript1.js">
<script src="javascript2.js">
on my page, then javascript1.js should load before javascript2.js
Thanks.
EDIT: Thank you for your answers, but mine question is not only related with the order of js files. I want to load js files as quickly as possible without using any 3rd party js library. The solution which is similar can be found at www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/, but using this does not guarantee the order of the files for me, atleast.
There is no single "best" way of loading Javascript files. Different ways work best in different scenarios.
The normal way of loading Javascript files is to put the script tags in the head tag.
You can put some script tags inside the body tag instead, to make them load later. One common reason for this is to make the content of the page display without having to wait for the script to load.
The scripts are executed in the way that the tags are placed in the code. The execution of the code below a script tag waits for the Javascript to be executed first.
In your question you say that you want one script to load before the other, which can't be guaranteed by just using script tags in the code. Then you would have to generate the second script tag in the first Javascript and use document.write to put it in the page. To make the scripts execute in that order, you can just use your script tags the way that you do, and the order is guaranteed.
Note: You should specify the type attribute in the script tags, so that the tags validate without errors. You need to include the closing tag for the script tags.
<script type="text/javascript" src="javascript1.js"></script>
<script type="text/javascript" src="javascript2.js"></script>
As others have said, the scripts are loaded in order of placement on the page (unless they are wrapped in javascript to be loaded in later)
Putting the script tags at the bottom of the page can assist with the loading process for both old and new browsers. Although some scripts might (like modenizer) need to be loaded earlier on in the process. A good example can be seen at http://html5boilerplate.com/ on the index code sample.
Edit:
Following your edit, there is this info which can help
<script type="text/javascript">
document.writeln("<script type='text/javascript' src='Script1.js'><" + "/script>");
document.writeln("<script type='text/javascript' src='Script2.js'><" + "/script>");
</script>
The full documentation on this can be read here (including crevets of other methods) http://blogs.msdn.com/b/kristoffer/archive/2006/12/22/loading-javascript-files-in-parallel.aspx
HTML is a top down procedural language so anything that is posted first gets executed first. Hence the order which you wrote is correct.
Your web browser will execute javascript files in the order they are declared, so in your example:
<script src="javascript1.js">
<script src="javascript2.js">
javascript1.js will be executed before javascript2.js.
As for the most ideal way, this is all very subjective. I prefer progressive enhancement when using javascript so declare my javascript as the last element on a page, since it is not required for the site to function, any user can see the content and use the site even while the javascript is downloading.
I also prefer bundling all my scripts together, in a minified form, so the browser only has to make one request to get my javascript.
There is a school of thought that using parallel loading is good. This means the scripts are loaded like the GA snippet provided by google by using JS. A good way of doing this is to use modernizr. This script enables you to load the scripts when they are needed. You would need to include the modernizr script in the traditional way and then write some JS to load the other script when required.
The Best Answer Can Be Found Here:Here:http://www.html5rocks.com/en/tutorials/speed/script-loading/
Ideally do this if you need to load them in some particular order (In case of dynamically added scripts):
`
['//other-domain.com/1.js',
'2.js']
.forEach(function(src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.head.appendChild(script);
});
`
And this for no order:
`
['//other-domain.com/1.js',
'2.js'
].forEach(function(src) {
var script = document.createElement('script');
script.src = src;
document.head.appendChild(script);
});
`
But if you just need static scripts then just ado this at the end of your body as suggested by many others:
`<script src="//other-domain.com/1.js"></script>
<script src="2.js"></script>`

Are external scripts in the head of an HTML document guaranteed to execute before scripts contained within the body?

I'm trying to execute some inline javascript within an HTML page as early in page processing as possible that makes use of library functions in an external .js file.
While I've always seen that putting library scripts in the head, and client scripts in the body just seems to work, I can't find documentation anywhere that says that external scripts included within the head of a document are guaranteed to run before script located within the body of a document (except on the w3schools site, but they don't count as a reputable reference)
To illustrate, I'm wondering about the User-Agent behavior for HTML that looks like this:
<html>
<head>
<script type="text/javascript src="libraryModule.js"></script>
</head>
<body>
<script type="text/javascript">
// is this guaranteed to run after the external script?
// or is it possible this module that the external library
// adds to the global namespace won't be there yet?
var result = ModuleInExternalLibrary.DoLibraryThing();
</script>
</body>
</html>
Is this documented anywhere? I can't find anything in the W3C spec or any good post that sums up the behavior in this area of all the major browsers. Please provide a link.
Am I stuck having to wait until the onload event fires in order to guarantee that external scripts have executed?
JavaScript statements that appear between <script> and </script> tags are executed in order of appearance. So yes, it is guaranteed, unless you are doing something clever like deferred loading or something similar.
Execution of JavaScript Programs

How to load one JavaScript file from another?

How do you load one JavaScript file from another JavaScript file, like CSS?
In CSS we use write #import url("mycss.css");.
Is there any way to do it in JavaScript?
There's no #import-ish function/method in Javascript, but you can simply append a script to the <head> tag like so:
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = '/path/to/js/file';
document.getElementsByTagName('head')[0].appendChild(newScript);
Or like Edgar mentioned right before me you can use jQuery.
Yes. If you want in pure JavaScript, you have to create dynamically a script tag, and append it to the document.
Yes. If you use the jQuery library, you can use the $.getScript method.
$.getScript("another_script.js");
Just because no-one has mentioned it yet, there's another option, which doesn't require any fancy libraries or tricky coding, document.write. In principal, it would look like this, although see below for a caveat:
document.write('<script src="myscript.js" type="text/javascript"></script>');
This will be executed upon completely parsing the script tag, and if you put your script tag in the head, the new script tag will also be in the head, right after the one being executed. Take care to execute it directly rather than when the document has been loaded (as in a $(function(){}) callback. This is what I use:
(function(){
function load(script) {
document.write('<'+'script src="'+script+'" type="text/javascript"><' + '/script>');
}
load("script1.js");
load("script2.js");
load("etc.js");
})();
The enclosing function is just there to not pollute the global namespace.
The caveat (and why the 'script' that is broken up above) is that there may be no ending script tags within a script tag, the HTML parser doesn't know it's part of the script. There's an other question on that subject.
Javascript itself doesn't provide any help with modularization other than the ability to eval a string. But this is a common-enough need that most big javascript frameworks have come up with their own solutions, and more recently, there has been an effort to standardize those APIs in the requirejs project. If you're using a framework like Dojo or jQuery, you're probably just best off learning to use their facilities, but if not, requirejs is a lightweight standalone tool. You basically just add
<script data-main="scripts/main" src="scripts/require.js"></script>
to your <head> section, and then put your own javascript inside some wrapper code like this (stolen from the require.js site):
require(["helper/util"], function() {
//This function is called when scripts/helper/util.js is loaded.
require.ready(function() {
//This function is called when the page is loaded
//(the DOMContentLoaded event) and when all required
//scripts are loaded.
});
});
use const dataName =require('./fileName.js');

Categories