my first JavaScript

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.

  1. It separates the HTML and JavaScript code and makes the code look clean and easy to understand.
  2. External JavaScript code can be reused in multiple HTML webpages.
  3. 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 tag or after the closing tag, so that first our complete webpage loads and then the external JavaScript files are loaded. This way, even if we have large JavaScript files, our webpage will not slow down because of it.

Conclusion:

So this tutorial covers all the ways to include JavaScript code into HTML web page and the best practices too. In the next tutorial, we will learn how we can get an output from JavaScript code so that we can start doing some coding and see JavaScript code running.

Источник

Re-use code with includes

JavaScript files can be added to the includes/ folder to define simple scripts, constants or macros that can be reused across your project. Each file in the includes folder will be made available for use within your other SQL or JavaScript files.

It’s also possible to add JavaScript to a .sqlx file by wrapping it in a js <. >block. Note: Functions, constants or macros defined in this way will only be available within the .sqlx file they are defined in, not across the whole project.

If you are new to JavaScript, the examples below should cover some common use cases. MDN is a useful learning resource if you’d like to learn more.

Example: Defining and using constants

Create a new file in your project under the includes/ folder, such as:

includes/constants.js
1const PROJECT_ID = "my_project_name"; 2module.exports = ;

Note that in order to use functions or constants elsewhere in the project, they must be exported using the module.exports = "> syntax.

Example: Using an include

You can reference any include function, constant, or macro by using its file name without the .js extension, followed by the name of the exported function or constant.

For example, to reference the constant PROJECT_ID in the file includes/constants.js :

definitions/query.sqlx
1SELECT * FROM $.PROJECT_ID>.my_schema_name.my_table_name

The query will be compiled into the following SQL before it is run:

1SELECT * FROM my_project_name.my_schema_name.my_table_name

Example: Writing functions

Functions enable you to reuse the same block of SQL logic across many different scripts. Functions take 0 or more named parameters and must return a string.

In the example below, the function countryGroup() takes as input the name of the country code field and returns a CASE statement that maps country codes to country groups.

includes/country_mapping.js
1function countryGroup(countryCodeField)  2 return `CASE 3 WHEN $ IN ("US", "CA") THEN "NA" 4 WHEN $ IN ("GB", "FR", "DE", "IT", "PL") THEN "EU" 5 WHEN $ IN ("AU") THEN $ 6 ELSE "Other countries" 7 END`; 8> 9 10module.exports = ;

This function can be used in a SQLX file:

definitions/revenue_by_country_group.sqlx
1SELECT 2 $.countryGroup("country_code")> AS country_group, 3 SUM(revenue) AS revenue 4 FROM my_schema.revenue_by_country 5 GROUP BY 1

The query will be compiled into the following SQL before it is run:

1SELECT 2 CASE 3 WHEN country_code IN ("US", "CA") THEN "NA" 4 WHEN country_code IN ("GB", "FR", "DE", "IT", "PL") THEN "EU" 5 WHEN country_code IN ("AU") THEN country_code 6 ELSE "Other countries" 7 END AS country_group, 8 SUM(revenue) AS revenue 9 FROM my_schema.revenue_by_country 10 GROUP BY 1

Example: An include with parameters: groupBy

The example below defines a groupBy() function that takes as input a number of fields to group by and generates a corresponding GROUP BY statement:

includes/utils.js
1function groupBy(n)  2 var indices = []; 3 for (var i = 1; i  n; i++)  4 indices.push(i); 5 > 6 return `GROUP BY $.join(", ")>`; 7> 8 9module.exports = ;

This function can be used in a SQL query definitions/example.sqlx :

1SELECT field1, 2 field2, 3 field3, 4 field4, 5 field5, 6 SUM(revenue) AS revenue 7 FROM my_schema.my_table 8$.groupBy(5)>

The query will be compiled into the following SQL before it is run:

1SELECT field1, 2 field2, 3 field3, 4 field4, 5 field5, 6 SUM(revenue) AS revenue 7 FROM my_schema.my_table 8 GROUP BY 1, 2, 3, 4, 5

Example: Generating queries

Functions can be used to generate entire queries. This is a powerful feature that can be useful if you need to create several datasets which share a similar structure.

The example below includes a function that aggregates all metrics (using SUM ) and groups by every dimension.

includes/script_builder.js
1function renderScript(table, dimensions, metrics)  2 return ` 3 SELECT 4 $.map((field) => `$ AS $ `).join(",\\n")>, 5 $.map((field) => `SUM($ ) AS $ `).join(",\\n")> 6 FROM $table> 7 GROUP BY $.map((field, i) => `$ + 1>`).join(", ")> 8 `; 9> 10module.exports = ;

This function can be used in a SQL query definitions/stats_per_country_and_device.sqlx :

1$.renderScript( 2 ref("source_table"), 3 ["country", "device_type"], 4 ["revenue", "pageviews", "sessions"])>

Note that calls to functions such as ref() should be made in the SQL file itself and passed to the include function so that dependencies are configured correctly.

The query will be compiled into the following SQL before it is run:

1SELECT country AS country, 2 device_type AS device_type, 3 SUM(revenue) AS revenue, 4 SUM(pageviews) AS pageviews, 5 SUM(sessions) AS sessions 6 FROM my_schema.source_table 7 GROUP BY 1, 2

What's next

Use JavaScript files

Learn how to define several actions in a single Javascript file.

Источник

Оцените статью