Javascript dynamically load text file




















The setAttribute method allows us to set the src value for the script we'd like to load. We seal the deal by adding our script element to the bottom of our body element via appendChild. Take a moment to look at all that is contained here. Mainly, we have a script element that contains some code to dynamically load a file called easing. To see all of this in action, save your HTML document and preview it in your favorite browser. What we visually see doesn't really tell us much. What we need to do is go undercover and inspect the live version of our DOM!

For that, we need to bring up the browser developer tools and Inspect the page to see exactly what the browser sees. When we do this, notice that our dynamically created script element shows up in the DOM:. To go even further, we can inspect the Network traffic and see that the easing. If easing. That will ensure you can see the external script file being requested and then loaded.

At this point, we have looked at the basics of how to load an external script file using just a few lines of JavaScript. Article Contributed By :. Easy Normal Medium Hard Expert. Writing code in comment? Please use ide. Load Comments. What's New. Most popular in JavaScript. Most visited in Web Technologies. Installation of Node. We could do something silly like call setInterval and continually check if the library has loaded by looking for its global window variable:.

However, this code is ugly and wastes resources. Instead, we should listen directly for the script element to fire its onload event:. The code would be even easier to read if we used Promises , which would allow us to chain multiple scripts together to load one after the other. To load a. It sounds a lot more fancy than it really is.

Lets see how it all comes together:. After that, the function sets out to create the element using the appropriate DOM methods , assign it the proper attributes, and finally, add it to the end of the HEAD section.



0コメント

  • 1000 / 1000