Reputation: 4568
All JavaScript files I have seen so far have had the extension .js
, for example as in <script src="MyScriptFile.js" language="javascript" />
.
I am wondering whether this is a requirement? Or, is any extension valid? For instance, could I use MyScriptFile.txt
or MyScriptFile
and still have a perfectly valid JavaScript file working in all major web browsers?
I have not been able to find information about this in the JavaScript specification.
Upvotes: 3
Views: 2149
Reputation: 21
They can be anything. I just tried it based on the answers given here and it worked. It can be very beneficial when you need a dynamic script file, which is how I got here. I was able to build my script file in php for building a dynamic list of Google map markers being pulled from a database. Many thanks for the answers. My script file link src is to a file with a php extension that outputs the javascript text.
Upvotes: 2
Reputation: 7156
No, they could also be .whatever
and they would work anyways.
The script:
<script type="text/javascript" src="file.txt"></script>
Tells the html to use that file as a JS, no matter the extention.
I used to write my JS with php and so they could contain PHP code, but you can get in trouble sometimes if you do that.
You should also look at the Search Engines optimisation; search engines are expecting .js
files to be .js
and they can go askew because of wrong extensions and your site may lose some points and positions.
An important point is the server, as it "knows" the file contents is javascript if they are .js
extension and so it treats it in the right manner, and does what's expected.
The best practice is to use proper file extensions. (But this does not mean you can't use others).
Upvotes: 2