Question

I am searching how to combine many code inside a javascript file.

For example, I have 2 codes inside this js:

 First: --> code is for timer function,   
 Second: -> for login action.

I need the First code this time, so I can write it like :

 <script src="javascript.js?action=timer"></script>   

But I don't know how to do with GET method in js. It's very easy in PHP, but I don't know the method in JS. What can I do next? Thanks for helping....

Was it helpful?

Solution

That is a poor way to approach what you want, one of the better methods being something like:

<script src="javascript.js"></script>
<script>Application.init("timer");</script>

But you could do something like this in PHP:

<?php header("Content-type: application/javascript"); ?>

var action = <?php echo $_GET["action"]; ?>;
console.log(action);

With the embed code:

<script src="javascript.php?action=timer"></script>
                       ^^^^ Note we're looking at a PHP file.

If you're determined to have the .js? extension, you can create a rewrite rule to accommodate that.

OTHER TIPS

You dont need to do like this just import the js in your page and call the appropriate function.

Are you trying to create new functions inside the same file? In that case, you can simply use the standard function keyword.

If you are trying to auto-run a function when you load the script, I'd have to ask why? It is normal to manually run the function when you need it -- sometime after the script is loaded.

<script src="javascript.js"></script>
timer();  // invoke the function

Those GET parameters are not available in your JavaScript. You can separate the files into two distinct ones (quite easy) or you can process things on the server side so the correct stuff is returned (unnecessarily complicated). If you just want to pass in more parameters on load, try putting the code from those files into a function and then calling the function with some arguments when the page loads.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top