Reputation: 75
I have a script in AngularJS that only runs when I have this line
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js">
now I want my method to have its own javascript file so I can just reference that,but there is no import or anything.
How is this traditionally done where you import a link? should I just go download that file at that link and import it into the project?
Upvotes: 0
Views: 385
Reputation: 21782
To do this this in your one file, you would need to load the file from the <script>
tag manually. It's not too hard. By adding a script tag, you would have to wait for it to load until your code ran. Here is how you would do it. At the top of your file, you would add the following.
// Create a script tag manually
var angularJsScriptTag = document.createElement('script');
// Set the src on the script tag to your CDN version of AngularJS
angularJsScriptTag.src = "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js";
// The script won't load until you append it to the document. So append it to the head
document.head.appendChild(angularJsScriptTag);
// Add a listener for when the AngularJS had loaded. Once it's loaded, run your own code.
angularJsScriptTag.onload = function() {
// Call a function to execute your code in this onload callback.
// This code won't run until that AngularJS script has loaded.
}
Upvotes: 1
Reputation: 1
If you have a vanilla JS file to include, you would simply use the same <script src="myFile.js">
tag in the html file to bring it in.
If the file is hosted somewhere that you trust (and is not going to change causing a problem for your application) then you can go ahead and link it the same way you have here. however otherwise it would be prudent to host it along with your application.
possible duplicate of How do I include a JavaScript file in another JavaScript file?
Upvotes: 0