0

How can I access modules in my js file:

<script type="text/javascript" src="script.js?modules=test,cookie"></script>

4 Answers 4

2

give an ID to your script tag

<script type="text/javascript" src="script.js?modules=test,cookie" id='YOURID'></script>

then in your js file use :

jsSrc  = document.getElementById("YOURID").src;
var jsQry = jsSrc.substr(jsSrc.indexOf("?"));
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for, thx for all your responses guys
1

a super hacky way to do it would be to give your script tag an id attribute and then access it from within the script itself, pulling out and parsing the src attribute :)

<script id="myscript" src="script.js?modules=a,b"></script>

in jquery you could do:

$(function(){
    var modules = $('#myscript').attr('src').split('=')[1].split(',');
});

like i said, super hacky, but could work!

Comments

1

Assuming you mean:

How can I read the query string used to load my JS file in my JS?

Then the most reliable way is to generate the JS server side and include the data that way.

For example:

<?php
    header('Content-Type: application/javascript');
    echo 'var modules = ' . json_encode($_GET['modules']);
?>

A less reliable, but entirely client side, method is to find the last script element in the document and parse the URI.

var scripts = document.getElementsByTagName('script');
var myScript = scripts[scripts.length - 1];
var uri = myScript.src;
// and so on

Comments

1

script.js should be a file with server side logic that sends js modules as response according to the input. But i don't recommend this approach (you miss caching).

Place your modules into separate files.

(or merge them for faster download)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.