\n
In this case, you would have a separate file, named myScript.js, that would reside in the same folder as your HTML document. The benefits of using external JavaScript files are that using them
\n\nCreating a .js file
\nCreating an external JavaScript file is similar to creating an HTML file or another other type of file. To replace the embedded JavaScript with an external JavaScript file, follow these steps:
\n\n In Sublime Text, choose File→New File.
\n \n Copy everything between and from MyFirstProgram.html and paste it into your new .js file.
\nNotice that external JavaScript files don’t contain elements, just the JavaScript.
\n \n Save your new file as countToTen.js in the same folder as MyFirstProgram.html.
\n \n In MyFirstProgram.html, modify your script element to add a src attribute, like this:
\n \n
\n\nYour copy should now look like this:
\n\n\n\n Hello, HTML!\n \n\n\n Let’s Count to 10 with JavaScript!
\n \n\n
\nYour new file, countToTen.js, should look like this:
\nfunction countToTen(){\n var count = 0;\n while (count < 10) {\n count++;\n document.getElementById(“theCount”).innerHTML +=\ncount + “
“;\n }\n}
\nAfter you’ve saved both files, you should see them inside your project in the Sublime Text sidebar.
\n
Viewing multiple files in your project folder in Sublime Text.
\nKeeping your .js files organized
\nExternal JavaScript files can sometimes get to be very large. In many cases, it’s a good idea to break them up into smaller files, organized by the type of functions they contain. For example, one JavaScript file may contain scripts related to the user login capabilities of your program, while another may contain scripts related to the blogging capabilities.
\nFor small programs, however, it’s usually sufficient to have just one file, and many people will name their single JavaScript file something generic, such as app.js, main.js, or scripts.js.
\nJavaScript files don’t need to be in the same folder as the HTML file that includes them. In fact, you should create a new folder specifically for storing your external JavaScript files. Most people call this something like js.
\nFollow these steps to create a js folder inside of your Sublime Text project and move your js file into it:
\n\n Right-click on the name of your project in the Sublime Text sidebar.
\nA submenu appears.
\n \n Choose New Folder from the submenu.
\nA Folder Name text area appears at the bottom of the Sublime Text window.
\n \n Enter js into the folder name text field and press Enter.
\nA new folder called js appears in the sidebar.
\n \n Open countToTen.js and choose File→Save As and save it in your new js folder.
\n \n Right-click on the version of countToTen.js that’s outside of your folder and choose Delete File from the submenu.
\n \n Open up MyFirstProgram.js and change your script element to reflect the new location of your js file, like this:
\n \n
\n\nWhen you open MyFirstProgram.html in your browser (or simply click refresh), it should look exactly like it did before you moved the JavaScript file into its own folder.
","inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https://www.dummies.com/article/technology/programming-web-design/javascript/including-external-javascript-files-in-your-code-142566/"]}]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://www.dummies.com/"},{"@type":"ListItem","position":2,"name":"Technology","item":"https://www.dummies.com/category/articles/technology-33512"},{"@type":"ListItem","position":3,"name":"Programming Web Design","item":"https://www.dummies.com/category/articles/programming-web-design-33592"},{"@type":"ListItem","position":4,"name":"JavaScript","item":"https://www.dummies.com/category/articles/javascript-33603"},{"@type":"ListItem","position":5,"name":"Including External JavaScript Files in Your Code"}]},{"@type":"Organization","url":"https://www.dummies.com/","logo":"https://www.dummies.com/img/logo.f7c39ad9.svg"},{"@type":"ImageObject","id":"#primaryimage","@id":"https://www.dummies.com/article/technology/programming-web-design/javascript/including-external-javascript-files-in-your-code-142566//#primaryimage","url":"https://www.dummies.com/wp-content/uploads/481994.image0.jpg","caption":"Viewing multiple files in your project folder in Sublime Text","height":425,"width":522},{"@type":"Article","id":"#article","headline":"Including External JavaScript Files in Your Code dummies","datePublished":"2016-03-26T07:38:39+00:00","dateModified":"2016-03-26T07:38:39+00:00","author":[{"@type":"Person","name":"Chris Minnick","url":"https://www.dummies.com/author/chris-minnick-9070"},{"@type":"Person","name":"Eva Holland","url":"https://www.dummies.com/author/eva-holland-9071"}],"image":{"@id":"https://www.dummies.com/article/technology/programming-web-design/javascript/including-external-javascript-files-in-your-code-142566//#primaryimage"}}]}{"appState":{"pageLoadApiCallsStatus":true},"articleState":{"article":{"headers":{"creationTime":"2016-03-26T07:38:39+00:00","modifiedTime":"2016-03-26T07:38:39+00:00","timestamp":"2022-02-24T16:46:03+00:00"},"data":{"breadcrumbs":[{"name":"Technology","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33512"},"slug":"technology","categoryId":33512},{"name":"Programming & Web Design","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33592"},"slug":"programming-web-design","categoryId":33592},{"name":"JavaScript","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33603"},"slug":"javascript","categoryId":33603}],"title":"Including External JavaScript Files in Your Code","strippedTitle":"including external javascript files in your code","slug":"including-external-javascript-files-in-your-code","canonicalUrl":"","seo":{"metaDescription":"","noIndex":0,"noFollow":0},"content":"<p>The most popular way to include JavaScript in HTML documents is by using the <span class=\"code\">src</span> attribute of the script element. A script element with a <span class=\"code\">src</span> attribute works exactly like a script element with JavaScript between the tags, except that if you use the <span class=\"code\">src</span> attribute, the JavaScript is loaded into the HTML document from a separate file. Here’s an example of a script element with a <span class=\"code\">src</span> attribute:</p>\n<pre class=\"code\"><script src=“myScript.js”></script></pre>\n<p>In this case, you would have a separate file, named <span class=\"code\">myScript.js</span>, that would reside in the same folder as your HTML document. The benefits of using external JavaScript files are that using them</p>\n<ul class=\"level-one\">\n <li><p class=\"first-para\">Keeps your HTML files neater and less cluttered</p>\n </li>\n <li><p class=\"first-para\">Makes your life easier because you need to modify JavaScript in only one place when something changes or when you make a bug fix</p>\n </li>\n</ul>\n<h2 id=\"tab1\" >Creating a .js file</h2>\n<p>Creating an external JavaScript file is similar to creating an HTML file or another other type of file. To replace the embedded JavaScript with an external JavaScript file, follow these steps:</p>\n<ol class=\"level-one\">\n <li><p class=\"first-para\">In Sublime Text, choose File→New File.</p>\n </li>\n <li><p class=\"first-para\">Copy everything between<b> </b><span class=\"code\"><script></span><b> </b>and<b> </b><span class=\"code\"></script></span><b> </b>from<b> </b><span class=\"code\">MyFirstProgram.html</span><b> </b>and paste it into your new<b> </b><span class=\"code\">.js</span><b> </b>file.</p>\n<p class=\"child-para\">Notice that external JavaScript files don’t contain <span class=\"code\"><script></span> elements, just the JavaScript.</p>\n </li>\n <li><p class=\"first-para\">Save your new file as<b> </b><span class=\"code\">countToTen.js</span><b> </b>in the same folder as<b> </b>MyFirstProgram.html<b>.</b></p>\n </li>\n <li><p class=\"first-para\">In<b> </b><span class=\"code\">MyFirstProgram.html</span>, modify your script element to add a<b> </b><span class=\"code\">src</span> attribute, like this:</p>\n </li>\n</ol>\n<pre class=\"code\"><script src=“countToTen.js”></script</pre>\n<p>Your copy should now look like this:</p>\n<pre class=\"code\"><!DOCTYPE html>\n<html>\n<head>\n <title>Hello, HTML!</title>\n <script src=“countToTen.js”></script>\n</head>\n<body onload=“countToTen();”>\n <h1>Let’s Count to 10 with JavaScript!</h1>\n <p id=“theCount”></p>\n</body>\n</html></pre>\n<p>Your new file, <span class=\"code\">countToTen.js</span>, should look like this:</p>\n<pre class=\"code\">function countToTen(){\n var count = 0;\n while (count < 10) {\n count++;\n document.getElementById(“theCount”).innerHTML +=\ncount + “<br>“;\n }\n}</pre>\n<p>After you’ve saved both files, you should see them inside your project in the Sublime Text sidebar.</p>\n<div class=\"imageBlock\" style=\"width:522px;\"><img src=\"https://www.dummies.com/wp-content/uploads/481994.image0.jpg\" height=\"425\" alt=\"Viewing multiple files in your project folder in Sublime Text.\" width=\"522\"/><div class=\"imageCaption\">Viewing multiple files in your project folder in Sublime Text.</div></div>\n<h2 id=\"tab2\" >Keeping your .js files organized</h2>\n<p>External JavaScript files can sometimes get to be very large. In many cases, it’s a good idea to break them up into smaller files, organized by the type of functions they contain. For example, one JavaScript file may contain scripts related to the user login capabilities of your program, while another may contain scripts related to the blogging capabilities.</p>\n<p>For small programs, however, it’s usually sufficient to have just one file, and many people will name their single JavaScript file something generic, such as <span class=\"code\">app.js</span>, <span class=\"code\">main.js</span>, or <span class=\"code\">scripts.js</span>.</p>\n<p>JavaScript files don’t need to be in the same folder as the HTML file that includes them. In fact, you should create a new folder specifically for storing your external JavaScript files. Most people call this something like js.</p>\n<p>Follow these steps to create a <span class=\"code\">js</span> folder inside of your Sublime Text project and move your <span class=\"code\">js</span> file into it:</p>\n<ol class=\"level-one\">\n <li><p class=\"first-para\">Right-click on the name of your project in the Sublime Text sidebar.</p>\n<p class=\"child-para\">A submenu appears.</p>\n </li>\n <li><p class=\"first-para\">Choose New Folder from the submenu.</p>\n<p class=\"child-para\">A Folder Name text area appears at the bottom of the Sublime Text window.</p>\n </li>\n <li><p class=\"first-para\">Enter js into the folder name text field and press Enter.</p>\n<p class=\"child-para\">A new folder called <span class=\"code\">js</span> appears in the sidebar.</p>\n </li>\n <li><p class=\"first-para\">Open<b> </b><span class=\"code\">countToTen.js</span><b> </b>and choose File→Save As and save it in your new<b> </b><span class=\"code\">js</span><b> </b>folder.</p>\n </li>\n <li><p class=\"first-para\">Right-click on the version of<b> </b><span class=\"code\">countToTen.js</span><b> </b>that’s outside of your folder and choose Delete File from the submenu.</p>\n </li>\n <li><p class=\"first-para\">Open up<b> </b><span class=\"code\">MyFirstProgram.js</span> and change your script element to reflect the new location of your <span class=\"code\">js</span><b> </b>file, like this:</p>\n </li>\n</ol>\n<pre class=\"code\"><script src=“js/countToTen.js”></script></pre>\n<p>When you open <span class=\"code\">MyFirstProgram.html</span> in your browser (or simply click refresh), it should look exactly like it did before you moved the JavaScript file into its own folder.</p>","description":"<p>The most popular way to include JavaScript in HTML documents is by using the <span class=\"code\">src</span> attribute of the script element. A script element with a <span class=\"code\">src</span> attribute works exactly like a script element with JavaScript between the tags, except that if you use the <span class=\"code\">src</span> attribute, the JavaScript is loaded into the HTML document from a separate file. Here’s an example of a script element with a <span class=\"code\">src</span> attribute:</p>\n<pre class=\"code\"><script src=“myScript.js”></script></pre>\n<p>In this case, you would have a separate file, named <span class=\"code\">myScript.js</span>, that would reside in the same folder as your HTML document. The benefits of using external JavaScript files are that using them</p>\n<ul class=\"level-one\">\n <li><p class=\"first-para\">Keeps your HTML files neater and less cluttered</p>\n </li>\n <li><p class=\"first-para\">Makes your life easier because you need to modify JavaScript in only one place when something changes or when you make a bug fix</p>\n </li>\n</ul>\n<h2 id=\"tab1\" >Creating a .js file</h2>\n<p>Creating an external JavaScript file is similar to creating an HTML file or another other type of file. To replace the embedded JavaScript with an external JavaScript file, follow these steps:</p>\n<ol class=\"level-one\">\n <li><p class=\"first-para\">In Sublime Text, choose File→New File.</p>\n </li>\n <li><p class=\"first-para\">Copy everything between<b> </b><span class=\"code\"><script></span><b> </b>and<b> </b><span class=\"code\"></script></span><b> </b>from<b> </b><span class=\"code\">MyFirstProgram.html</span><b> </b>and paste it into your new<b> </b><span class=\"code\">.js</span><b> </b>file.</p>\n<p class=\"child-para\">Notice that external JavaScript files don’t contain <span class=\"code\"><script></span> elements, just the JavaScript.</p>\n </li>\n <li><p class=\"first-para\">Save your new file as<b> </b><span class=\"code\">countToTen.js</span><b> </b>in the same folder as<b> </b>MyFirstProgram.html<b>.</b></p>\n </li>\n <li><p class=\"first-para\">In<b> </b><span class=\"code\">MyFirstProgram.html</span>, modify your script element to add a<b> </b><span class=\"code\">src</span> attribute, like this:</p>\n </li>\n</ol>\n<pre class=\"code\"><script src=“countToTen.js”></script</pre>\n<p>Your copy should now look like this:</p>\n<pre class=\"code\"><!DOCTYPE html>\n<html>\n<head>\n <title>Hello, HTML!</title>\n <script src=“countToTen.js”></script>\n</head>\n<body onload=“countToTen();”>\n <h1>Let’s Count to 10 with JavaScript!</h1>\n <p id=“theCount”></p>\n</body>\n</html></pre>\n<p>Your new file, <span class=\"code\">countToTen.js</span>, should look like this:</p>\n<pre class=\"code\">function countToTen(){\n var count = 0;\n while (count < 10) {\n count++;\n document.getElementById(“theCount”).innerHTML +=\ncount + “<br>“;\n }\n}</pre>\n<p>After you’ve saved both files, you should see them inside your project in the Sublime Text sidebar.</p>\n<div class=\"imageBlock\" style=\"width:522px;\"><img src=\"https://www.dummies.com/wp-content/uploads/481994.image0.jpg\" height=\"425\" alt=\"Viewing multiple files in your project folder in Sublime Text.\" width=\"522\"/><div class=\"imageCaption\">Viewing multiple files in your project folder in Sublime Text.</div></div>\n<h2 id=\"tab2\" >Keeping your .js files organized</h2>\n<p>External JavaScript files can sometimes get to be very large. In many cases, it’s a good idea to break them up into smaller files, organized by the type of functions they contain. For example, one JavaScript file may contain scripts related to the user login capabilities of your program, while another may contain scripts related to the blogging capabilities.</p>\n<p>For small programs, however, it’s usually sufficient to have just one file, and many people will name their single JavaScript file something generic, such as <span class=\"code\">app.js</span>, <span class=\"code\">main.js</span>, or <span class=\"code\">scripts.js</span>.</p>\n<p>JavaScript files don’t need to be in the same folder as the HTML file that includes them. In fact, you should create a new folder specifically for storing your external JavaScript files. Most people call this something like js.</p>\n<p>Follow these steps to create a <span class=\"code\">js</span> folder inside of your Sublime Text project and move your <span class=\"code\">js</span> file into it:</p>\n<ol class=\"level-one\">\n <li><p class=\"first-para\">Right-click on the name of your project in the Sublime Text sidebar.</p>\n<p class=\"child-para\">A submenu appears.</p>\n </li>\n <li><p class=\"first-para\">Choose New Folder from the submenu.</p>\n<p class=\"child-para\">A Folder Name text area appears at the bottom of the Sublime Text window.</p>\n </li>\n <li><p class=\"first-para\">Enter js into the folder name text field and press Enter.</p>\n<p class=\"child-para\">A new folder called <span class=\"code\">js</span> appears in the sidebar.</p>\n </li>\n <li><p class=\"first-para\">Open<b> </b><span class=\"code\">countToTen.js</span><b> </b>and choose File→Save As and save it in your new<b> </b><span class=\"code\">js</span><b> </b>folder.</p>\n </li>\n <li><p class=\"first-para\">Right-click on the version of<b> </b><span class=\"code\">countToTen.js</span><b> </b>that’s outside of your folder and choose Delete File from the submenu.</p>\n </li>\n <li><p class=\"first-para\">Open up<b> </b><span class=\"code\">MyFirstProgram.js</span> and change your script element to reflect the new location of your <span class=\"code\">js</span><b> </b>file, like this:</p>\n </li>\n</ol>\n<pre class=\"code\"><script src=“js/countToTen.js”></script></pre>\n<p>When you open <span class=\"code\">MyFirstProgram.html</span> in your browser (or simply click refresh), it should look exactly like it did before you moved the JavaScript file into its own folder.</p>","blurb":"","authors":[{"authorId":9070,"name":"Chris Minnick","slug":"chris-minnick","description":"Chris Minnick is an author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Learn more at watzthis.com.","_links":{"self":"https://dummies-api.dummies.com/v2/authors/9070"}},{"authorId":9071,"name":"Eva Holland","slug":"eva-holland","description":"Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. With Chris Minnick, she founded WatzThis?, a company focused on training and course development. ","_links":{"self":"https://dummies-api.dummies.com/v2/authors/9071"}}],"primaryCategoryTaxonomy":{"categoryId":33603,"title":"JavaScript","slug":"javascript","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33603"}},"secondaryCategoryTaxonomy":{"categoryId":33599,"title":"Coding","slug":"coding","_links":{"self":"https://dummies-api.dummies.com/v2/categories/33599"}},"tertiaryCategoryTaxonomy":{"categoryId":0,"title":null,"slug":null,"_links":null},"trendingArticles":null,"inThisArticle":[{"label":"Creating a .js file","target":"#tab1"},{"label":"Keeping your .js files organized","target":"#tab2"}],"relatedArticles":{"fromBook":[{"articleId":207619,"title":"JavaScript For Dummies Cheat Sheet","slug":"javascript-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207619"}},{"articleId":207525,"title":"Coding with JavaScript For Dummies Cheat Sheet","slug":"coding-with-javascript-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207525"}},{"articleId":203241,"title":"10 Online Tools to Help You Write Better JavaScript","slug":"10-online-tools-to-help-you-write-better-javascript","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/203241"}},{"articleId":203240,"title":"10 JavaScript Frameworks and Libraries to Learn Next","slug":"10-javascript-frameworks-and-libraries-to-learn-next","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/203240"}},{"articleId":144114,"title":"List of HTML5 APIs for Coding with JavaScript","slug":"list-of-html5-apis-for-coding-with-javascript","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/144114"}}],"fromCategory":[{"articleId":209047,"title":"jQuery For Dummies Cheat Sheet","slug":"jquery-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/209047"}},{"articleId":207619,"title":"JavaScript For Dummies Cheat Sheet","slug":"javascript-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207619"}},{"articleId":207525,"title":"Coding with JavaScript For Dummies Cheat Sheet","slug":"coding-with-javascript-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207525"}},{"articleId":207485,"title":"JavaScript For Kids For Dummies Cheat Sheet","slug":"javascript-for-kids-for-dummies-cheat-sheet","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/207485"}},{"articleId":203241,"title":"10 Online Tools to Help You Write Better JavaScript","slug":"10-online-tools-to-help-you-write-better-javascript","categoryList":["technology","programming-web-design","javascript"],"_links":{"self":"https://dummies-api.dummies.com/v2/articles/203241"}}]},"hasRelatedBookFromSearch":false,"relatedBook":{"bookId":281669,"slug":"coding-with-javascript-for-dummies","isbn":"9781119056072","categoryList":["technology","programming-web-design","javascript"],"amazon":{"default":"https://www.amazon.com/gp/product/1119056071/ref=as_li_tl?ie=UTF8&tag=wiley01-20","ca":"https://www.amazon.ca/gp/product/1119056071/ref=as_li_tl?ie=UTF8&tag=wiley01-20","indigo_ca":"http://www.tkqlhce.com/click-9208661-13710633?url=https://www.chapters.indigo.ca/en-ca/books/product/1119056071-item.html&cjsku=978111945484","gb":"https://www.amazon.co.uk/gp/product/1119056071/ref=as_li_tl?ie=UTF8&tag=wiley01-20","de":"https://www.amazon.de/gp/product/1119056071/ref=as_li_tl?ie=UTF8&tag=wiley01-20"},"image":{"src":"https://www.dummies.com/wp-content/uploads/coding-with-javascript-for-dummies-cover-9781119056072-203x255.jpg","width":203,"height":255},"title":"Coding with JavaScript For Dummies","testBankPinActivationLink":"","bookOutOfPrint":false,"authorsInfo":"\n <p><b data-author-id=\"9070\">Chris Minnick</b> is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. <b data-author-id=\"9071\">Eva Holland</b> is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis? </p>","authors":[{"authorId":9070,"name":"Chris Minnick","slug":"chris-minnick","description":"Chris Minnick is an author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Learn more at watzthis.com.","_links":{"self":"https://dummies-api.dummies.com/v2/authors/9070"}},{"authorId":9071,"name":"Eva Holland","slug":"eva-holland","description":"Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. With Chris Minnick, she founded WatzThis?, a company focused on training and course development. ","_links":{"self":"https://dummies-api.dummies.com/v2/authors/9071"}}],"_links":{"self":"https://dummies-api.dummies.com/v2/books/"}},"collections":[],"articleAds":{"footerAd":"<div class=\"du-ad-region row\" id=\"article_page_adhesion_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_adhesion_ad\" data-refreshed=\"false\" \r\n data-target = \"[{"key":"cat","values":["technology","programming-web-design","javascript"]},{"key":"isbn","values":["9781119056072"]}]\" id=\"du-slot-6217b64b9de06\"></div></div>","rightAd":"<div class=\"du-ad-region row\" id=\"article_page_right_ad\"><div class=\"du-ad-unit col-md-12\" data-slot-id=\"article_page_right_ad\" data-refreshed=\"false\" \r\n data-target = \"[{"key":"cat","values":["technology","programming-web-design","javascript"]},{"key":"isbn","values":["9781119056072"]}]\" id=\"du-slot-6217b64b9e97f\"></div></div>"},"articleType":{"articleType":"Articles","articleList":null,"content":null,"videoInfo":{"videoId":null,"name":null,"accountId":null,"playerId":null,"thumbnailUrl":null,"description":null,"uploadDate":null}},"sponsorship":{"sponsorshipPage":false,"backgroundImage":{"src":null,"width":0,"height":0},"brandingLine":"","brandingLink":"","brandingLogo":{"src":null,"width":0,"height":0}},"primaryLearningPath":"Advance","lifeExpectancy":null,"lifeExpectancySetFrom":null,"dummiesForKids":"no","sponsoredContent":"no","adInfo":"","adPairKey":[]},"status":"publish","visibility":"public","articleId":142566},"articleLoadedStatus":"success"},"listState":{"list":{},"objectTitle":"","status":"initial","pageType":null,"objectId":null,"page":1,"sortField":"time","sortOrder":1,"categoriesIds":[],"articleTypes":[],"filterData":{},"filterDataLoadedStatus":"initial","pageSize":10},"adsState":{"pageScripts":{"headers":{"timestamp":"2022-05-16T12:59:10+00:00"},"adsId":0,"data":{"scripts":[{"pages":["all"],"location":"header","script":"<!--Optimizely Script-->\r\n<script src=\"https://cdn.optimizely.com/js/10563184655.js\"></script>","enabled":false},{"pages":["all"],"location":"header","script":"<!-- comScore Tag -->\r\n<script>var _comscore = _comscore || [];_comscore.push({ c1: \"2\", c2: \"15097263\" });(function() {var s = document.createElement(\"script\"), el = document.getElementsByTagName(\"script\")[0]; s.async = true;s.src = (document.location.protocol == \"https:\" ? \"https://sb\" : \"http://b\") + \".scorecardresearch.com/beacon.js\";el.parentNode.insertBefore(s, el);})();</script><noscript><img src=\"https://sb.scorecardresearch.com/p?c1=2&c2=15097263&cv=2.0&cj=1\" /></noscript>\r\n<!-- / comScore Tag -->","enabled":true},{"pages":["all"],"location":"footer","script":"<!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->\r\n<script type='text/javascript'>\r\n(function(){var g=function(e,h,f,g){\r\nthis.get=function(a){for(var a=a+\"=\",c=document.cookie.split(\";\"),b=0,e=c.length;b<e;b++){for(var d=c[b];\" \"==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};\r\nthis.set=function(a,c){var b=\"\",b=new Date;b.setTime(b.getTime()+6048E5);b=\"; expires=\"+b.toGMTString();document.cookie=a+\"=\"+c+b+\"; path=/; \"};\r\nthis.check=function(){var a=this.get(f);if(a)a=a.split(\":\");else if(100!=e)\"v\"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(\":\"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case \"v\":return!1;case \"r\":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(\":\")),!c}return!0};\r\nthis.go=function(){if(this.check()){var a=document.createElement(\"script\");a.type=\"text/javascript\";a.src=g;document.body&&document.body.appendChild(a)}};\r\nthis.start=function(){var t=this;\"complete\"!==document.readyState?window.addEventListener?window.addEventListener(\"load\",function(){t.go()},!1):window.attachEvent&&window.attachEvent(\"onload\",function(){t.go()}):t.go()};};\r\ntry{(new g(100,\"r\",\"QSI_S_ZN_5o5yqpvMVjgDOuN\",\"https://zn5o5yqpvmvjgdoun-wiley.siteintercept.qualtrics.com/SIE/?Q_ZID=ZN_5o5yqpvMVjgDOuN\")).start()}catch(i){}})();\r\n</script><div id='ZN_5o5yqpvMVjgDOuN'><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>\r\n<!--END WEBSITE FEEDBACK SNIPPET-->","enabled":false},{"pages":["all"],"location":"header","script":"<!-- Hotjar Tracking Code for http://www.dummies.com -->\r\n<script>\r\n (function(h,o,t,j,a,r){\r\n h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)};\r\n h._hjSettings={hjid:257151,hjsv:6};\r\n a=o.getElementsByTagName('head')[0];\r\n r=o.createElement('script');r.async=1;\r\n r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv;\r\n a.appendChild(r);\r\n })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');\r\n</script>","enabled":false},{"pages":["article"],"location":"header","script":"<!-- //Connect Container: dummies --> <script src=\"//get.s-onetag.com/bffe21a1-6bb8-4928-9449-7beadb468dae/tag.min.js\" async defer></script>","enabled":true},{"pages":["homepage"],"location":"header","script":"<meta name=\"facebook-domain-verification\" content=\"irk8y0irxf718trg3uwwuexg6xpva0\" />","enabled":true},{"pages":["homepage","article","category","search"],"location":"footer","script":"<!-- Facebook Pixel Code -->\r\n<noscript>\r\n<img height=\"1\" width=\"1\" src=\"https://www.facebook.com/tr?id=256338321977984&ev=PageView&noscript=1\"/>\r\n</noscript>\r\n<!-- End Facebook Pixel Code -->","enabled":true}]}},"pageScriptsLoadedStatus":"success"},"searchState":{"searchList":[],"searchStatus":"initial","relatedArticlesList":[],"relatedArticlesStatus":"initial"},"routeState":{"name":"Article3","path":"/article/technology/programming-web-design/javascript/including-external-javascript-files-in-your-code-142566/","hash":"","query":{},"params":{"category1":"technology","category2":"programming-web-design","category3":"javascript","article":"including-external-javascript-files-in-your-code-142566"},"fullPath":"/article/technology/programming-web-design/javascript/including-external-javascript-files-in-your-code-142566/","meta":{"routeType":"article","breadcrumbInfo":{"suffix":"Articles","baseRoute":"/category/articles"},"prerenderWithAsyncData":true},"from":{"name":null,"path":"/","hash":"","query":{},"params":{},"fullPath":"/","meta":{}}},"dropsState":{"submitEmailResponse":false,"status":"initial"},"sfmcState":{"newsletterSignupStatus":"initial"}}Including External JavaScript Files in Your Code
The most popular way to include JavaScript in HTML documents is by using the src attribute of the script element. A script element with a src attribute works exactly like a script element with JavaScript between the tags, except that if you use the src attribute, the JavaScript is loaded into the HTML document from a separate file. Here’s an example of a script element with a src attribute:
In this case, you would have a separate file, named myScript.js, that would reside in the same folder as your HTML document. The benefits of using external JavaScript files are that using them
Creating a .js file
Creating an external JavaScript file is similar to creating an HTML file or another other type of file. To replace the embedded JavaScript with an external JavaScript file, follow these steps:
In Sublime Text, choose File→New File.
Copy everything between and from MyFirstProgram.html and paste it into your new .js file.
Notice that external JavaScript files don’t contain elements, just the JavaScript.
Save your new file as countToTen.js in the same folder as MyFirstProgram.html.
In MyFirstProgram.html, modify your script element to add a src attribute, like this:
Your copy should now look like this:
Hello, HTML!
Let’s Count to 10 with JavaScript!
Your new file, countToTen.js, should look like this:
function countToTen(){
var count = 0;
while (count < 10) {
count++;
document.getElementById("theCount").innerHTML +=
count + "
";
}
}
After you’ve saved both files, you should see them inside your project in the Sublime Text sidebar.
Viewing multiple files in your project folder in Sublime Text.
Keeping your .js files organized
External JavaScript files can sometimes get to be very large. In many cases, it’s a good idea to break them up into smaller files, organized by the type of functions they contain. For example, one JavaScript file may contain scripts related to the user login capabilities of your program, while another may contain scripts related to the blogging capabilities.
For small programs, however, it’s usually sufficient to have just one file, and many people will name their single JavaScript file something generic, such as app.js, main.js, or scripts.js.
JavaScript files don’t need to be in the same folder as the HTML file that includes them. In fact, you should create a new folder specifically for storing your external JavaScript files. Most people call this something like js.
Follow these steps to create a js folder inside of your Sublime Text project and move your js file into it:
Right-click on the name of your project in the Sublime Text sidebar.
A submenu appears.
Choose New Folder from the submenu.
A Folder Name text area appears at the bottom of the Sublime Text window.
Enter js into the folder name text field and press Enter.
A new folder called js appears in the sidebar.
Open countToTen.js and choose File→Save As and save it in your new js folder.
Right-click on the version of countToTen.js that’s outside of your folder and choose Delete File from the submenu.
Open up MyFirstProgram.js and change your script element to reflect the new location of your js file, like this:
When you open MyFirstProgram.html in your browser (or simply click refresh), it should look exactly like it did before you moved the JavaScript file into its own folder.
About This Article
This article is from the book:
About the book authors:
Chris Minnick is an accomplished author, trainer, and web developer who has worked on web and mobile projects for both small and major businesses. Eva Holland is an experienced writer and trainer who has designed and taught online, in-person, and video courses. They are cofounders of WatzThis?
This article can be found in the category: