- Инклюд в яваскрипте 19 марта 2007
- Решение
- Модули
- Неймспейсы
- Include JavaScript in HTML
- Script tag Attributes and its Uses
- JavaScript in HTML Webpage
- 1. Script tag with JavaScript Code in Element
- 1. Script tag with JavaScript Code in Element
- 3. JavaScript Code in an External File
- Including External JavaScript Syntax:
- Advantages of External JavaScript File:
- JavaScript Code in External File Example:
- Including JavaScript in HTML Page: Best Practice
- Conclusion:
Инклюд в яваскрипте 19 марта 2007
Современный крупный сайт невозможно представить без яваскрипта, и чем ближе разработчик желает приблизить свое приложение к тому, что называется вебом 2.0, тем больше становится доля яваскрипта в общем объеме программного кода.
Большое число скриптов труднее структурировать, а элемент каждой страницы превращается в нечто подобное:
Но это полбеды. Ведь файл Page/Index.js зависит от Company.js, а тот в свою очередь от Widget/Person.js и Widget/Address.js. А те от Widget/Date.js и Box.js и т. д.
Причем загружать их нужно именно в указанной последовательности. А если страниц много? А если, например, хочется разделить какой-нибудь из виджетов на два файла? Или добавить пару новых классов? Или объединить несколько скриптов в один большой файл для ускорения загрузки?
Ведь все зависимости удобно было бы хранить непосредственно в js-файлах.
Почти в любом «взрослом» языке для этого существует конструкция include. В яваскрипте ее нет, но при должном желании ее удается сымитировать. Представьте, как удобно было бы написать в начале Company.js что-нибудь вроде:
js.include('als.Template'); js.include('als.utils.Text'); js.include('als.widget.Box'); js.include('domain.ClientsInfo.Widget.Properties'); js.include('domain.ClientsInfo.widget.Address'); js.include('domain.ClientsInfo.widget.Person'); .
Что же мешает так сделать? Или веб 2.0 способен лишь на раскрашивание кнопок?
Решение
Какие препятствия поджидают нас? Во-первых, инклюд должен полностью отрабатывать до начала выполнения кода. Во-вторых, не исключены зависимости нескольких файлов от одного модуля и загружать его дважды совсем не хочется. В-третьих, требуется какой-нибудь механизм загрузки файлов с сервера. Для начала препятствий хватит.
На дворе 2007 год, и подавляющее большинство браузеров поддерживают XHTTPRequest именно им и следует воспользоваться. Этот объект работает в двух режимах: асинхронном (когда указывается функция обратного вызова) и синхронном (запрос происходит непосредственно во время вызова xhttp.open() ). Нам нужен второй: при этом код загрузится прямо на месте js.include . А дальше достаточно выполнить eval(xhttp.responseText) :
01
02
03
04
05
06
07
08
09
10
11
12
13
14
//js.js js = <>; js.loadedModules = <>; ┘ js.include = function(path) < if(js.loadedModules[path]) return; var transport = js.getXHTTPTransport(); transport.open('GET', js.rootUrl + path.replace(/\./g, '/') + '.js', false); transport.send(null); var code = transport.responseText; eval(code); >
Вот и все. Теперь перед загрузкой скриптов достаточно подключить js.js и инклюд работает.
Модули
Полезно вынести в отдельную команду объявление загруженного модуля. Например, в начале каждого файла писать js.module(«js.Event») , а саму функцию сделать так:
Теперь инклюд будет знать о том, что скрипт с данным адресом уже загружен, даже если js-файл подключен с помощью тега .
Ну а кроме того, каждая загрузка скрипта отдельный запрос на сервер. Поэтому если всегда необходимо загружать группу файлов как единый набор, оптимально объединить их в один большой. Тогда и серверу придется выполнять меньше операций, и трафик между браузером и сервером сократится. А нам в итоге нужно написать:
js.module("domain.Class1"); domain.Class1 = function() js.module("domain.Class2"); js.include("domain.Class1"); domain.Class2 = function() domain.Class2.prototype = new domain.Class1();
То, что объявление модуля вынесено в самое начало файла (до инклюдов), позволяет избежать зацикливания даже в тех случаях, когда между файлами возникает циклическая зависимость.
Неймспейсы
Раз уж мы раскладываем файлы по папкам вроде domain/ClientsInfo/Widget/Person.js, логично было бы в файле Person.js иметь описание класса domain.ClientsInfo.Widget.Person. Но если попытаться создать класс domain.ClientsInfo.Widget.Person при несуществующем domain.ClientsInfo.Widget, интерпретатор яваскрипта выдаст ошибку. Между тем, проверять в начале каждого файла, что существует объект domain.ClientsInfo.Widget, а вместе с ним и domain.ClientsInfo, и просто domain, будет утомительно и громоздко.
Объявление неймспейса имен удобно вынести в функцию объявления модуля. Например, так:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
js.evalProperty = function(object, name, value) < if(object) < if(!object[name]) object[name] = value || true; return object[name]; >return null; > js.evalPath = function(path, context, value) < context = context || window; var pos = path.indexOf('.'); if(pos == -1) < return js.evalProperty(context, path, value); >else < var name = path.substring(0, pos); var path = path.substring(pos + 1); var obj = js.evalProperty(context, name, value); return js.evalPath(path, obj, value); >> js.module = function(path)
Загруженный код выполняется с помощью функции eval(). Это означает, что в «Мозилле» отладить его не удастся. Visual Studio более покладиста, но не балует подсветкой синтаксиса. Проблема решается подключением отлаживаемых скриптов тегом .
Include JavaScript in HTML
The JavaScript code can be inserted in HTML file by using the HTML tag. When an HTML document is loaded with the tag in the web browser, the browser processes the content enclosed inside the script tag as JavaScript code.
The script tag can contain either scripting statements or refer to an external JavaScript file. The script tag provides a src attribute that allows us to add a reference to an external script file.
JavaScript is the default scripting language for most of the browsers.
Script tag Attributes and its Uses
Following is the basic syntax of using a tag:
Similarly, we can use the tag to directly add the JavaScript code too, like this:
There are five attributes of script tag which are listed below in the table:
- true
- false
- text/ECMAScript
- text/javascript
- application/ECMAScript
- application/javascript
- text/VBScript
- true
- false
Now that we know about the tag which is used to include JavaScript code in a webpage, let’s see the various different ways in which we can do so.
JavaScript in HTML Webpage
You can use script tag inside an HTML web page to add JavaScript code in the following ways:
- In the HEAD element ( . )
- In the BODY element ( . )
- To include an External JavaScript File
Let’s cover all of this one by one along with code examples to help you understand them.
1. Script tag with JavaScript Code in Element
Let’s put the script tag inside the HTML head element. The script placed inside the head element is loaded with the webpage and gets executed if any defined event occurs.
The code given below shows how to use the tag inside the element of an HTML document to add some JavaScript code.
1. Script tag with JavaScript Code in Element
You can place a script tag inside the body element of an HTML document too. The script tag inside the body element runs when a web page starts loading in a web browser. Below is the code to show you how to place a element inside the element of an HTML document:
3. JavaScript Code in an External File
Whenever we put lengthy JavaScript code in an HTML document, it affects the readability and maintainability of the HTML document. In addition, sometimes there is a need to use the same JavaScript code in several web pages. In such cases, we can store the JavaScript code in an external file and save that file with the .js extension. All JavaScript code files should have an extension .JS and nothing else.
To link the external file, we can provide its location (URL) in the src attribute of the script tag.
Including External JavaScript Syntax:
This is the way by which we can add an external JavaScript file to our HTML file:
The type attribute is optional in the code example above.
Advantages of External JavaScript File:
Using an external JavaScript file has its own merits.
- It separates the HTML and JavaScript code and makes the code look clean and easy to understand.
- External JavaScript code can be reused in multiple HTML webpages.
- External JavaScript code can be cached in the browser. Once cached the browser will not load the JavaScript file again and again and will use the cached version of it. This will make your webpage loading fast.
JavaScript Code in External File Example:
The code given below shows you how to link an external JavaScript file with an HTML document.
this is the old text
The JavaScript code stored in a file with name jsfile.js
In the code above, we have defined a simple function in JavaScript, we will learn about JavaScript functions in upcoming tutorials.
Including JavaScript in HTML Page: Best Practice
In large projects, JavaScript code can be huge and there can be multiple external JavaScript files included in each HTML page using multiple tags. Yes, we can use multiple tags to include as many external JavaScript files as we want.
For example, if we have 3 JavaScript file, with names, one.js, two.js and three.js and we have to include all of these in our HTML page. We will use 3 tags in this case,
Now the question is, where should we put the above code in our HTML page. Should we put it inside the HEAD section of HTML code, or should we put it in the BODY section of our HTML page?
Well, if we put it in the HEAD section, then when our webpage will load, all the JavaScript files will be loaded first which can slow down our webpage loading, which is not good.
So, we should load the external JavaScript files used in a webpage, at last, means either just before the closing