I have an application where I load a div via an ajax call, or with jquery
$('#cont').load("something.html");
<div id="cont">
</div>
something.html looks like:
<script src="./js/test.js"></script>
<table>
.......blah....blah
</table>
I get:
jquery-1.12.0.min.js:4 Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
I have been going into the test.js file and just cutting and pasting the script to the beginning of something.html but this is a lot of redundant script. Many pages uses it and it becomes a pain to maintain.
Is there a way I can keep script loaded this way in a separate .js file?
When jQuery inserts HTML that contains <script> elements, it executes the scripts immediately. If it's a reference to an external script, it uses synchronous AJAX to load the script recursively, to emulate the way the browser loads scripts as it's loading an HTML file. This triggers the warning.
You could just ignore the warning, as synchronous AJAX isn't going away any time soon. But if you really want to get rid of it, you could split your load into two parts. Take the line that loads test.js out of something.html, and use:
$.getScript('./js/test.js', function() {
$("#cont").load('something.html');
});
Try breaking this into two operations. In your page, load your JS script using a normal script element with a reference to an external JS file:
<script src="./js/test.js"></script>
Then, do an AJAX call to get your content and load that into the target div in the AJAX call's success handler. The easiest way to do that in jQuery is with $.get():
<script>
$.get('/path/to/something.html', function(data) {
// set the contents of #cont to the HTML returned from the AJAX call
$('#cont').html(data);
});
</script>
If synchronous execution is not necessary for the script, you could try:
<script src="./js/test.js" async="async"></script>
<table>
.......blah....blah
</table>
Doing this means that there's no guarantee that your script would execute before the following <table> is parsed and rendered. Setting the async attribute means this can happen in any order.
The HTML5 spec is here:
The async and defer attributes are boolean attributes that indicate
how the script should be executed. The defer and async attributes must
not be specified if the src attribute is not present.
There are three possible modes that can be selected using these
attributes. If the async attribute is present, then the script will be
executed asynchronously, as soon as it is available. If the async
attribute is not present but the defer attribute is present, then the
script is executed when the page has finished parsing. If neither
attribute is present, then the script is fetched and executed
immediately, before the user agent continues parsing the page.
Support is pretty good for modern browsers:
IE 10+
FF 3.6+
Chrome 8+
Safari 5.1+
Opera 15+
Related
Here's the scenario, not sure what I'm missing.
Page A.htm makes an ajax request for page B.htm, and inserts the response into the page.
Page B.htm contains links to several other JS files, many of which contain a document.ready() function to initialize them.
This works fine when A.htm and B.htm are on the same server but not when they are on different servers.
What I think I'm seeing here, is that when page A and B are on different servers (cross domain ajax), the external resources are being returned asynchronously, or at least out of order, so scripts are executing expecting JQuery.UI to be loaded already, when it is not.
Appreciate any pointers or advice. Apologies for the poor explanation.
You are injecting HTML + script tags via jQuery. In this case *:
HTML content except scripts are injected in the document
Then all scripts are executed one by one
If a script is external then it is downloaded and executed asynchronously
Therefore an external or inline script that depends on jQuery UI might execute before jQuery UI.
One possible solution is to change the way your pages work:
Get rid of external scripts in pageb.html but keep inline scripts
Load the required scripts in pagea.html
Load pageb.html
Another solution is to roll your own jQuery function that will:
Strip all <script src> elements from HTML
Download and execute those scripts in order
Inject the remaining HTML
* The exact behavior is not documented. I had to look into the source code to infer the details.
you are correct in your impression that the issue is a difference in how the requests are handled cross-domain.
Here is a link to get you on the right track : How to make synchronous JSONP crossdomain call
However, you will have to actually re-achitect your solution somewhat to check if the resource has been loaded before moving on. There are many solutions (see the link)
You can set a timer interval and check for something in the dom, or another reasonable solution (despite it's lack of efficiency) is to create a "proxy" serverside (eg php) file on your server and have that file do the cross-domain request, then spit out the result.
Note that since jquery UI is a rather large file, it's conceivable that the cross-domain request finishes first, and executes immediately, even though jqueryUI is not loaded yet. In any case, you're going to have to start thinking about having your app react rather than follow a sequence.
I have a Java Web Application, and I'm wondering if the javascript files are downloaded with the HTML-body, or if the html body is loaded first, then the browser request all the JavaScript files.
The reason for this question is that I want to know if importing files with jQuery.getScript() would result in poorer performance. I want to import all files using that JQuery function to avoid duplication of JavaScript-imports.
The body of the html document is retrieved first. After it's been downloaded, the browser checks what resources need to be retrieved and gets those.
You can actually see this happen if you open Chrome Dev Console, go to network tab (make sure caching is disabled and logs preserved) and just refresh a page.
That first green bar is the page loading and the second chunk are the scripts, a stylesheet, and some image resources
The HTML document is downloaded first, and only when the browser has finished downloading the HTML document can it find out which scripts to fetch
That said, heavy scripts that don't influence the appearance of the HTML body directly should be loaded at the end of the body and not in the head, so that they do not block the rendering unless necessary
I'm wondering if the javascript are downloaded with the html body during a request
If it's part of that body then yes. If it's in a separate resource then no.
For example, suppose your HTML file has this:
<script type="text/javascript">
$(function () {
// some code here
});
</script>
That code, being part of the HTML file, is included in the HTML resource. The web server doesn't differentiate between what kind of code is in the file, it just serves the response regardless of what's there.
On the other hand, if you have this:
<script type="text/javascript" src="someFile.js"></script>
In that case the code isn't in the same file. The HTML is just referencing a separate resource (someFile.js) which contains the code. In that case the browser would make a separate request for that resource. Resulting in two requests total.
The HTML document is downloaded first, or at least it starts to download first. While it is parsed, any script includes that the browser finds are downloaded. That means that some scripts may finish loading before the document is completely loaded.
While the document is being downloaded, the browser parses it and displays as much as it can. When the parsing comes to a script include, the parsing stops and the browser will suspend it until the script has been loaded and executed, then the parsing continues. That means that
If you put a call to getScript instead of a script include, the behaviour will change. The method makes an asynchronous request, so the browser will continue parsing the rest of the page while the script loads.
This has some important effects:
The parsing of the page will be completed earlier.
Scripts will no longer run in a specific order, they run in the order that the loading completes.
If one script is depending on another, you have to check yourself that the first script has actually loaded before using it in the other script.
You can use a combination of script includes and getScript calls to get the best effect. You can use regular scripts includes for scripts that other scripts depend on, and getScript for scripts that are not affected by the effects of that method.
Instead of having an external .js file, we can inline Javascript directly in HTML, i.e.
Externalized version
<html>
<body>
<script type="text/javascript" src="/app.js"></script>
</body>
</html>
Inlined version
<html>
<body>
<script type="text/javascript">
// app.js inlined
</script>
</body>
</html>
However, it's not recommended:
https://developer.yahoo.com/performance/rules.html#external
Put javascript and css inline in a single minified html file to improve performance?
The main reason is caching and pre-compiling - in the externalized version, the browser can download, pre-compile and store the file once for multiple pages, while it cannot do the same for inlined version.
However, is it possible to do something along these lines:
Inlined keyed version
<html>
<body>
<script type="text/javascript" hash="abc">
// app.js inlined
</script>
</body>
</html>
That is, do this:
In the first invocation, send the whole script and somehow tell the browser that the script hash is abc
Later, when the browser loads that or other pages containing the same script, it will send this key as a cookie. The server will only render the contents of the script if the key has been received.
That is, if the browser already knows about the script, the server will render just this:
Inlined keyed version, subsequent fetches (of the same or other pages)
<html>
<body>
<script type="text/javascript" hash="abc">
</script>
</body>
</html>
where notably the script contents are empty.
This would allow for shorter script fetching with a natural fallback.
Is the above possible? If not, is some other alternative to the above possible?
I don't know of a way to do what you asked, so I'll provide an alternative that might still suit your needs.
If you're really after a low latency first page load, you could inline the script, and then after the page loads, load the script via url so that it's in the browser cache for future requests. Set a cookie once you've loaded the script by direct url, so that your server can determine whether to inline the script or provide the external script url.
first page load
<script>
// inlined my-script.js goes here.
</script>
<script>
$(function(){
// load it again, so it's in the browser cache.
// notice I'm not executing the script, just loading it.
$.ajax("my-script.js").then(function(){
// set a cookie marking this script as cached
});
});
</script>
second page load
<script src="my-script.js"></script>
Obviously, this has the drawback that it loads the script twice. It also adds additional complexity for you to take care of when you update your script with new code - you need to make sure you address the cookie being for a old version.
I wouldn't bother with all this unless you really feel the need to optimize the first page. It might be worth it in your case.
The Concept
Here's an interesting approach (after being bugged by notifications :P)
You could have the server render your script this way. Notice the weird type attribute. That's to prevent the script from executing. We'll get to that in a second.
<script type="text/cacheable" data-hash="9182n30912830192c83012983xm019283x">
//inline script
</script>
Then create a library that looks for these scripts with weird types, get the innerHTML of these scripts, and execute them in the global context as if they were normally executing (via eval or new Function). This makes them execute like normal scripts. Here's a demo:
<script type="text/cacheable" data-hash="9182n30912830192c83012983xm019283x">
alert(a);
</script>
<script type="text/cacheable" data-hash="9182n30912830192c83012983xm019283x">
alert(b);
</script>
<script>
// Let's say we have a global
var a = "foo";
var b = "bar"
// Getting the source
var scripts = Array.prototype.slice.call(
document.querySelectorAll('script[type="text/cacheable"]')
);
scripts.forEach(function(script){
// Grabbing
var source = script.innerHTML;
// Create a function (mind security on this one)
var fn = new Function(source);
// Execute in the global scope
fn.call(window);
});
</script>
However...
Since you have the script source (the innerHTML), you can cache them somewhere locally (like in localStorage) and use the hash as its identifier. Then you can store the same hash in the cookie, where future page-requests can tell the server "Hey, I have cached script with [hash]. Don't print the script on the page anymore". Then you'll get this in future requests:
<script type="text/cacheable" data-hash="9182n30912830192c83012983xm019283x"></script>
That covers up the first half. The second phase is when your library sees an empty script. The other thing your library should do is when it sees an empty script, it should look up for that script with that hash in your local storage, get the script's source and execute it like you just did in the first place.
The Catch
Now there's always a trade-off in everything, and I'll highlight what I can think of here:
Pros
You only need one request for everything. Initial pageload contains scripts, subsequent pages become lighter because of the missing code, which is already cached by then.
Instant cache busting. Assuming the hash and code are 1:1, then changing the content should change the hash.
Cons
This assumes that pages are dynamic and are never cached. That's because if you happen to create a new script, with new hash, but had the client cache the page, then it will still be using the old hashes thus old scripts.
Initial page load will be heavy due to inlined scripts. But this can be overcome by compressing the source using a minifier on the server. Overhead of minification can also be overcome by caching minified results on the server.
Security. You'll be using eval or new Function. This poses a big threat when unauthorized code manages to sneak in. In addition, the threat is persistent because of the caching.
Out of sync pages. What happens if you get an empty script, whose hash is not in the cache? Perhaps the user deleted local storage? You'll have to issue a request to the server for it. Since you want the source, you'll have to have AJAX.
Scripts are not "normal". Your script is best put at the end of the page so that all inline scripts will be parsed by then. This means your scripts execute late and never in the time they get parsed by the browser.
Storage limits. localStorage has a size limit of 5-10MB, depending on which browser we're talking about. Cookies are limited to 4KB generally.
Request size. Note that cookies are shipped up to the server on request and down to the browser on response. That additional load might be more of a hassle than it is for good.
Added server-side logic. Because you need to know what needs to be added, you need to program your server to do it. This makes the client-side implementation dependent on the server. Switching servers (say from PHP to Python) wouldn't be as easy, as you need to port over the implementation.
If your <script> is not introduced as type=text/javascript, it will simply not be executed.
So you could have many tags like theses:
<script type="text/hashedjavascript" hash="abc">...</script>
<script type="text/hashedjavascript" hash="efg">...</script>
Then when the DOM is loaded, pick one and evaluate it.
I made an example here: http://codepen.io/anon/pen/RNGQEM
But it smells, real bad. It's definitely better to fetch two different files.
Actually what you should do, is have a single file my-scripts.js that contains the code for each of your script, wrapped in a function
// file: my-scripts.js
function script_abc(){
// what script abc is supposed to do
}
function script_efg(){
// what script efg is supposed to do
}
Then execute whatever your cookie tells you to. This is how AMD builders concatenate multiples files in one.
Also look for an AMD library such as requirejs
Edit: I misunderstood your question, removed the irrelevant part.
I have a couple of questions about the attributes async & defer for the <script> tag which to my understanding only work in HTML5 browsers.
One of my sites has two external JavaScript files that currently sit just above the </body> tag; the first is jquery sourced from google and the second is a local external script.
With respects to site load speed
Is there any advantage in adding async to the two scripts I have at the bottom of the page?
Would there be any advantage in adding the async option to the two scripts and putting them at the top of the page in the <head>?
Would this mean they download as the page loads?
I assume this would cause delays for HTML4 browsers, but would it speed up page load for HTML5 browsers?
Using <script defer src=...
Would loading the two scripts inside <head> with the attribute defer the same affect as having the scripts before </body>?
Once again I assume this would slow up HTML4 browsers.
Using <script async src=...
If I have two scripts with async enabled
Would they download at the same time?
Or one at a time with the rest of the page?
Does the order of scripts then become a problem? For example one script depends on the other so if one downloads faster, the second one might not execute correctly etc.
Finally am I best to leave things as they are until HTML5 is more commonly used?
This image explains normal script tag, async and defer
Async scripts are executed as soon as the script is loaded, so it
doesn't guarantee the order of execution (a script you included at
the end may execute before the first script file )
Defer scripts guarantees the order of execution in which they appear
in the page.
Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
Keep your scripts right before </body>. Async can be used with scripts located there in a few circumstances (see discussion below). Defer won't make much of a difference for scripts located there because the DOM parsing work has pretty much already been done anyway.
Here's an article that explains the difference between async and defer: http://peter.sh/experiments/asynchronous-and-deferred-javascript-execution-explained/.
Your HTML will display quicker in older browsers if you keep the scripts at the end of the body right before </body>. So, to preserve the load speed in older browsers, you don't want to put them anywhere else.
If your second script depends upon the first script (e.g. your second script uses the jQuery loaded in the first script), then you can't make them async without additional code to control execution order, but you can make them defer because defer scripts will still be executed in order, just not until after the document has been parsed. If you have that code and you don't need the scripts to run right away, you can make them async or defer.
You could put the scripts in the <head> tag and set them to defer and the loading of the scripts will be deferred until the DOM has been parsed and that will get fast page display in new browsers that support defer, but it won't help you at all in older browsers and it isn't really any faster than just putting the scripts right before </body> which works in all browsers. So, you can see why it's just best to put them right before </body>.
Async is more useful when you really don't care when the script loads and nothing else that is user dependent depends upon that script loading. The most often cited example for using async is an analytics script like Google Analytics that you don't want anything to wait for and it's not urgent to run soon and it stands alone so nothing else depends upon it.
Usually the jQuery library is not a good candidate for async because other scripts depend upon it and you want to install event handlers so your page can start responding to user events and you may need to run some jQuery-based initialization code to establish the initial state of the page. It can be used async, but other scripts will have to be coded to not execute until jQuery is loaded.
HTML5: async, defer
In HTML5, you can tell browser when to run your JavaScript code. There are 3 possibilities:
<script src="myscript.js"></script>
<script async src="myscript.js"></script>
<script defer src="myscript.js"></script>
Without async or defer, browser will run your script immediately, before rendering the elements that's below your script tag.
With async (asynchronous), browser will continue to load the HTML page and render it while the browser load and execute the script at the same time.
With defer, browser will run your script when the page finished parsing. (not necessary finishing downloading all image files. This is good.)
Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script.
The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. Whereas the defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.
Source & further details: here.
Faced same kind of problem and now clearly understood how both will works.Hope this reference link will be helpful...
Async
When you add the async attribute to your script tag, the following will happen.
<script src="myfile1.js" async></script>
<script src="myfile2.js" async></script>
Make parallel requests to fetch the files.
Continue parsing the document as if it was never interrupted.
Execute the individual scripts the moment the files are downloaded.
Defer
Defer is very similar to async with one major differerence. Here’s what happens when a browser encounters a script with the defer attribute.
<script src="myfile1.js" defer></script>
<script src="myfile2.js" defer></script>
Make parallel requests to fetch the individual files.
Continue parsing the document as if it was never interrupted.
Finish parsing the document even if the script files have downloaded.
Execute each script in the order they were encountered in the document.
Reference :Difference between Async and Defer
async and defer will download the file during HTML parsing. Both will not interrupt the parser.
The script with async attribute will be executed once it is downloaded. While the script with defer attribute will be executed after completing the DOM parsing.
The scripts loaded with async doesn't guarantee any order. While the scripts loaded with defer attribute maintains the order in which they appear on the DOM.
Use <script async> when the script does not rely on anything.
when the script depends use <script defer>.
Best solution would be add the <script> at the bottom of the body. There will be no issue with blocking or rendering.
Good practice is to keep all the files in your source folder to load source files fast. You need to download all the script, style, icon, and image-related files and put these files into your project folder.
Create these folders in your project to keep different source files and then load the required files into the pages from this folder.
JS: to keep script-related files.
CSS: to keep style-related files.
images: to keep image/icon-related files
fonts: to keep font-related files
When to use defer and async attributes on the <script> tag
defer attribute: First the defer attribute will download the script file and then wait for HTML parsing. After the end of the HTML parsing, the script will execute. In other words, it will guarantee all the scripts will execute after the HTML parsing.
The defer attribute is useful when the script is used for DOM manipulations.
async attribute: The async attribute will download the script file and execute without waiting for the end of HTML parsing. In other words, it does not guarantee that all the scripts will execute after the HTML parsing.
The async attribute is useful when the script is not used for DOM manipulation. Sometimes you need a script only for server-side operations or for handling cache or cookies, but not for DOM manipulations.
Useful link when to use defer and async:
https://stackoverflow.com/a/68929270/7186739
I think Jake Archibald presented us some insights back in 2013 that might add even more positiveness to the topic:
https://www.html5rocks.com/en/tutorials/speed/script-loading/
The holy grail is having a set of scripts download immediately without blocking rendering and execute as soon as possible in the order they were added. Unfortunately HTML hates you and won’t let you do that.
(...)
The answer is actually in the HTML5 spec, although it’s hidden away at the bottom of the script-loading section.
"The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "force-async" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "force-async" flag must first be unset…".
(...)
Scripts that are dynamically created and added to the document are async by default, they don’t block rendering and execute as soon as they download, meaning they could come out in the wrong order. However, we can explicitly mark them as not async:
[
'//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);
});
This gives our scripts a mix of behaviour that can’t be achieved with plain HTML. By being explicitly not async, scripts are added to an execution queue, the same queue they’re added to in our first plain-HTML example. However, by being dynamically created, they’re executed outside of document parsing, so rendering isn’t blocked while they’re downloaded (don’t confuse not-async script loading with sync XHR, which is never a good thing).
The script above should be included inline in the head of pages, queueing script downloads as soon as possible without disrupting progressive rendering, and executes as soon as possible in the order you specified. “2.js” is free to download before “1.js”, but it won’t be executed until “1.js” has either successfully downloaded and executed, or fails to do either. Hurrah! async-download but ordered-execution!
Still, this might not be the fastest way to load scripts:
(...) With the example above the browser has to parse and execute script to discover which scripts to download. This hides your scripts from preload scanners. Browsers use these scanners to discover resources on pages you’re likely to visit next, or discover page resources while the parser is blocked by another resource.
We can add discoverability back in by putting this in the head of the document:
<link rel="subresource" href="//other-domain.com/1.js">
<link rel="subresource" href="2.js">
This tells the browser the page needs 1.js and 2.js. link[rel=subresource] is similar to link[rel=prefetch], but with different semantics. Unfortunately it’s currently only supported in Chrome, and you have to declare which scripts to load twice, once via link elements, and again in your script.
Correction: I originally stated these were picked up by the preload scanner, they're not, they're picked up by the regular parser. However, preload scanner could pick these up, it just doesn't yet, whereas scripts included by executable code can never be preloaded. Thanks to Yoav Weiss who corrected me in the comments.
Rendering engine goes several steps till it paints anything on the screen.
it looks like this:
Converting HTML bytes to characters depending on encoding we set to the document;
Tokens are created according to characters. Tokens mean analyze characters and specify opening tangs and nested tags;
From tokens separated nodes are created. they are objects and according to information delivered from tokenization process, engine creates objects which includes all necessary information about each node;
after that DOM is created. DOM is tree data structure and represents whole hierarchy and information about relationship and specification of tags;
The same process goes to CSS. for CSS rendering engine creates different/separated data structure for CSS but it's called CSSOM (CSS Object Model)
Browser works only with Object models so it needs to know all information about DOM and CSSDOM.
The next step is combining somehow DOM and CSSOM. because without CSSOM browser do not know how to style each element during rendering process.
All information above means that, anything you provide in your html (javascript, css ) browser will pause DOM construction process. If you are familiar with event loop, there is simple rule how event loop executes tasks:
Execute macro tasks;
execute micro tasks;
Rendering;
So when you provide Javascript file, browser do not know what JS code is going to do and stops all DOM construction process and Javascript interptreter starts parsing and executing Javascript code.
Even you provide Javascript in the end of body tag, Browser will proceed all above steps to HTML and CSS but except rendering. it will find out Script tag and will stop until JS is done.
But HTML provided two additional options for script tag: async and defer.
Async - means execute code when it is downloaded and do not block DOM construction during downloading process.
Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.
It seems the behavior of defer and async is browser dependent, at least on the execution phase. NOTE, defer only applies to external scripts. I'm assuming async follows same pattern.
In IE 11 and below, the order seems to be like this:
async (could partially execute while page loading)
none (could execute while page loading)
defer (executes after page loaded, all defer in order of placement in file)
In Edge, Webkit, etc, the async attribute seems to be either ignored or placed at the end:
data-pagespeed-no-defer (executes before any other scripts, while page is loading)
none (could execute while page is loading)
defer (waits until DOM loaded, all defer in order of placement in file)
async (seems to wait until DOM loaded)
In newer browsers, the data-pagespeed-no-defer attribute runs before any other external scripts. This is for scripts that don't depend on the DOM.
NOTE: Use defer when you need an explicit order of execution of your external scripts. This tells the browser to execute all deferred scripts in order of placement in the file.
ASIDE: The size of the external javascripts did matter when loading...but had no effect on the order of execution.
If you're worried about the performance of your scripts, you may want to consider minification or simply loading them dynamically with an XMLHttpRequest.
Default - By default, as soon as the browser sees a script tag it downloads the file and then executes the script file. The script files are executed in the order of their occurrence.
async - The browser will download the script file and continue parsing HTML parallelly until the file is downloaded. The file is executed as soon as it is downloaded.
defer - The browser will download the script and do HTML parsing at the same time. After parsing is done, the script files are executed in the order of their occurrence.
Note:
In defer, the js files are executed in the order of their occurrence in the HTML file while in the case of the async attribute the script files are executed in the order of download time.
Both the async and defer attributes are used to load external JavaScript files asynchronously, which means that the HTML parsing and rendering process is not blocked while the external file is being downloaded and executed.
When you download a web page, 2 major things happen in your browser:
HTML Parsing
Loading of the scripts
2.1 Fetching scripts from the network
2.2 Executing the scripts line by line
However, there are some differences between the two attributes:
1.async attribute:
The async attribute allows the browser to download the script file asynchronously while continuing to parse the HTML document. Once the script file is downloaded, it will be executed immediately, regardless of whether or not the HTML document has finished parsing. This means that the script may execute before the rest of the page has loaded.
Example:
<script async src="script.js"></script>
2.defer attribute:
The defer attribute also downloads the script file asynchronously, but it will not be executed until the HTML document has finished parsing. This means that the script will be executed in the order in which it appears in the HTML document, and after the page has finished loading.
Example:
<script defer src="script.js"></script>
In general, the async attribute is used when the script file does not depend on other scripts or on the HTML document being fully loaded, while the defer attribute is used when the script file depends on other scripts or on the HTML document being fully loaded.
Summary:
Async is suitable if your script doesn’t contains DOM manipulation and other scripts doesn’t depend upon on this.
Eg: bootstrap cdn,jquery
Defer is suitable if your script contains DOM manipulation and other scripts depend upon on this.
Eg: <script src=”createfirst.js”> //let this will create element <script src=”showfirst.js”> //after createfirst create element it will show that.
Thus make it:
Eg: <script defer src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will
This will execute scripts in order.
But if i made:
Eg: <script async src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will
Then, this code might result unexpected results.
Coz: if html parser access createfirst script.It won’t stop DOM creation and starts downloading code from src .Once src got resolved/code got downloaded, it will execute immediately parallel with DOM.
What if showfirst.js execute first than createfirst.js.This might be possible if createfirst takes long time (Assume after DOM parsing finished).Then, showfirst will execute immediately.
In PHP there's a function called stream_wrapper_register. With that i can get the file contents of every PHP file that is about to be included. So that basically gives me control over the 'code' that will get parsed.
I was wondering if there's something like this in javascript too? So suppose i include my file:
<script type="text/javascript" src="js/myfile.js"></script>
My code in that file then sets up the stream wrapper (suppose this is available in JS too). Now i want to be able to get the file contents of every other javascript file that will be included:
<script type="text/javascript" src="js/somefile.js"></script>
<script type="text/javascript" src="js/someotherfile.js"></script>
But this ofcourse must happen before before the browser actually executes those files.
So is there a way to intercept that somehow?
$.ajax("/path/to/javascript.js").done(function(source) {
eval(transmogrifySourceCode(source));
});
I used the jQuery syntax because AJAX-style gets are much easier that way, and you'll have to provide your own transmogrifySourceCode function to edit the source before you load it.
I do wonder why you'd want to do, that, though. You should be in full control over your input source, so why not just excise the code you don't want on the server?
No, you can't. Alone for security reasons you won't be allowed to get every script's content.
For Opera, there is a special BeforeScript event which can be listened to from local user scripts.
So there is no (good) way to detect (dynamically added) <script> elements in a page and prevent them from loading and executing a script. Yet you could load the script files by ajax, respecting the same-origin-policy (!), and evaling their modified contents as #DavidEllis suggested.
Elsewise, you need to proxy all script inclusions over your server and modify them there.