Migrate non function script from HTML to JS file - javascript

As a begineer i am facing a problem, i followed an advise from several opinions to keep my HTML file clean, so i created a JS file and started migrating all scripts to a it, everything is Ok until i had to make this in it :
<script>
document.getElementById("mobile-toggle").addEventListener("click",function(){
document.getElementById("mobile-date").innerHTML = "Today is ...";});
</script>
When this script in is my HTML file it is run by the browser automatically but when i put it in the JS file, it simply don't work without being called with a function name, and that's what i want to avoid due to unobtrusive javascript recommendations, so my question is "is there a way to make a script from JS file to be run automatically without a call from HTML event ?
Thanks.

Include your script in the HTML with defer attribute. This will run the code when HTML is ready. You could place the script tag at the end before </body> as well, but I prefer having it on top.
<head>
<script src="/myscript.js" defer>
</head>
in myscript.js
(function() {
// your code goes here
})();
Wrapping this into a function gives your own scope and another wrap into parenthesis and () at the end will do the execution.

Related

I want to provide callback when clients load a javascript bundle library using snippet

my javascript library product is loaded asynchronously through the snippet in the client html.
As follows...
<html>
<head> ... </head>
<body>
<script>
...
!function(e,t){function n(e,t){
...
// loads javascript bundle library from server
...
}}(document, window.MYPRD||[]);
...
</script>
<script>
// if bundle library is not loaded, the following code will return an error since MYPRD object and myFunc() is not defined.
MYPRD.myFunc()
</script>
</body>
</html>
However, the snippet in that script tag is executed asynchronously and loads the bundle, so a callback function might be needed to ensure order when there are another executable codes in html.
I would also like to know how to guarantee the order from the client html using a load function, but I wish I could solve this issue in my snippet or my JavaScript bundle library.
What should I do? Please explain in detail. (I am a beginner in Javascript and web development.)
Thank you.

Only last javascript file linked with script tag is working

I linked all the javascript files in the header.php at atime. I included header.php in all pages
When I link the javascript files like this
<script src='js/home.js'></script>
<script src='js/disc.js'></script>
<script src='js/que.js'></script>
only last file js/que.js is working.
Make sure that the 'src' is referring to the correct file directory where the script is located. If you are using an IDE such as VS, then you may drag the file into the code and the IDE will automatically create the reference for you.
Unless you have problem with directory structure or you file name does not match with src attribute of script tag, there should not be any problem with. Please try to use type="text/javascript" and make sure your script tags are after header tag or just before </body> tag. Also keep sequence of files loading if any file depends on another file variable or any function. If it still does not work use try to see if there is any error in your code in console window.
I now I'm going to get voted down for this but oh well. I don't have enough points to comment which is what I would do but..oh well.
Okay it depends on what the scripts are doing. If you link the scripts in the head for you HTML page, and try a var element = document.getElementById("theID"); this will return null due to the fact that the browser has yet to read the HTML and hasn't had a chance to create a DOM (Document Object Model) tree. For a problem like this check out
<script>
function load() {
console.log("load event detected!");
}
window.onload = load;
</script>
This will assign window to an event/callback that will be invoked after the page has had time to load.
Look at where your JavaScript is used, and what it should be doing. Would those elements be rendered yet. Are you writing functions but not actually calling them (this happens A LOT)? It would be better if you described what the code was doing and your experience with HTML and JavaScript. Remember that the browser interprets the JavaScript as it encounters it, you can put script tags anywhere in your HTML file, not just in the head. Also are the .js files in the same directory as the HTML file or are the two non working .js files in the same directory as "js/que.js"? If not move them to the same file or use a relative or absolute path.

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>

JavaScript function not found in JSP

I have a few JSP pages, that include some JavaScript(jquery, jquery mobile and some javascript functions that I wrote).
When loading the pages and try to run my functions, I get in Firebug an error, that the function was not found. I have looked into the page source, and the function is there.
All the other jquery mobile functions work.
The only way to make my script work is to make a forced refresh(ctrl+f5).
Why is this happening? How can I fix it?
EDIT
It seems that a simple refresh would also work.
Here is the source code of the page:
http://pastebin.com/6sJnfPDQ
I have retagged your question to remove "Java" and "JSP", as this is irrelevant (server vs browser).
Once your JSP is rendered in the browser, please do look in the page source and see what happened to your tags.
make sure all of your js files are being loaded properly.
also make sure that your js files are being loaded in the proper order.
make sure that, where necessary, you're wrapping your JS in a document ready function of some type
also, I recommend that you add the type attribute to your script tags:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>

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>`

Categories