JavaScript: Compatibility, links and external files

If we look at the previous examples, we can see that it is very easy to display a text in a browser that supports JavaScript. But what can we do if a browser doesn't support JavaScript? We can use the <noscript> element. These scenarios are possible in the browser:

  • The browser doesn't support JavaScript, no matter whether it supports the <noscript>-element or not. If necessary it is ignored and the following elements are interpreted.

  • The browser supports JavaScript, and it is turned on. Then, the content of the <noscript>-elements isn't displayed.

  • The browser supports JavaScript, but it is turned off. Then everything inside the <noscript>-element. will be shown.

One should always remember the visitors who have JavaScript disabled, nut also note that all common browsers support JavaScript and fewer and fewer people turn JavaScript off.

External files

If you later write JavaScript programs that are needed on more than one page, it would be nonsensical to copy them to every single page - the effort for a change would be very substantial, as several files must be opened and edited.

Of course there is a solution: the src-attribute. In the script tag you can specify this attribute with the path to an external JavaScript file. The file extension for JavaScript files is .js. It is recommendable to create a folder for all external files, so that they are all collected in one place. Let us assume that the following file, test.js, is stored on a web server in the directory js:

This is how the file then can be included in an HTML document:

You should be careful, because the following fault can easily be made by beginners:

In this case, only the content of the external file will be shown. The content inside the script-tag will be ignored. If the src attribute is set, the content of the script-tags is ignored. If it isn't set, then the content of the tag is interpreted. If you want to show both sentences, you need to adjust the HTML file by separating our code in two <script>-tags.

JavaScript Links

JavaScript commands are often executed based on user inputs. For example, you can trigger an action with a mouse click. Before we show you a some examples, a new JavaScript command has to be introduced. Window.alert ("A great text") will open a modal window containing the text "A great text". These warning-windows look different in various browsers. The graphical layout of these windows can't be changed.

warning-windows in different browsers


Continue to part 3



Comment