How can I include a js file into another js file , so as to stick to the DRY principle and avoid duplication of code.
There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script'); imported.src = '/path/to/imported/script'; document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery $.getScript('/path/to/imported/script.js', function() { // script is now loaded and executed. // put your dependent JS here. });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With