MyBB Community Forums

Full Version: Inline JavaScript or external file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am developing a plugin which uses 24 lines of JavaScript and I was wondering if I should use it inline or externally. It is just raw JavaScript, it doesn't rely on a library. And it won't be used on all pages, just on a select few. What do you guys think?
I would do it in an external file. An external javascript file also gets cached by the browser so it will load from cache everytime it sees a reference to it. A normal MyBB page isn't cachable so your inline script will also have to loaded on every request.
I didn't know that, thank you. Usually I would have gone for an external JavaScript file, but since it was only 24 lines long I was considering inline JavaScript too.

There is an issue though, I am not able to use variables like {$tid} in an external JavaScript file, but if I write it inline it does work. How can I use these variables in an external JavaScript file? I tried looking at the files in the /jscripts/ folder but I couldn't figure it out.
You can't use {$tid} since Javascript doesn't support variable $ sign. Try using tid instead $tid
Thank your for your answer, but I believe you're wrong. JavaScript does support the dollar sign ($) in variable names. This is where I need to use the {$tid} variable:

var example = {
	0:"showthread.php?tid={$tid}",
	1:"showthread.php?tid={$tid}page=2",
};

I've tried what Yaldaram suggest and countless other things, but it just doesn't work in an external file, which I am calling in the showthread template. What do I need to do?
Try this;
var example = {
    0:"showthread.php?tid={$('tid')}",
    1:"showthread.php?tid={$('tid')}page=2",
};
What I do, is add variables inline like this:
$plugins->add_hook('showthread_start', 'pluginname_hook');
function pluginname_hook()
{
      global $headerinclude, $thread;
      $headerinclude .= '<script type="text/javascript">var THREAD_ID="'.$thread['tid'].'";</script>';
      $headerinclude .= '<script type="text/javascript" src="path/to/file.js"></script>';
}

You will be able to get THREAD_ID from any function now, either from an inline or external script.
Nothing says that external JavaScript can't be generated by PHP.

<script type='text/javascript' href='dynamic_js.php'></script>

Just make sure that your PHP which generates the JavaScript outputs the correct content-type header.